手动编组到线程 [英] Marshall to a thread manually

查看:55
本文介绍了手动编组到线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WinForms中,您具有Control.BeginInvoke(),这意味着您可以编组从后台线程到创建控件句柄的主UI线程的调用.

In WinForms, you have Control.BeginInvoke(), which means you can marshall a call from a background thread to the main UI thread that created the control's handle.

这很好,但是如何(在C#中)在两个标准"线程之间执行此操作?

This is fine, but how (in C#) would you do this between two "standard" threads?

我写了一条服务总线,它有一个处理器线程来使用消息.我要触发一个计时器,这会导致处理器线程执行某些操作,而不是在计时器线程中运行的代码.

I have written a service bus, which has a processor thread to consume messages. I want a timer to fire, that causes that processor thread to do something, rather than the code running in the timer's thread.

我当然可以使用线程同步(Monitor/using() {...}),但想知道它是如何正常完成的.

Of course I can use thread syncronisation (Monitor/using() {...}) but wondered how it was done normally.

推荐答案

不幸的是,这里很难给出答案,因为它高度依赖于线程的性质.

Unfortunately the answer is hard to give here because it's highly dependent upon the nature of the thread.

在线程之间封送并不是魔术.有一种潜在的机制使之成为可能.例如,在WinForms中,Control.Invoke样式函数通过消息传递起作用.有一条消息发布到UI线程,消息泵最终将泵出此消息并将其转换为元帅的呼叫.

Marshaling between threads isn't magic. There is an underlying mechanism which makes it possible to do. For example in WinForms, the Control.Invoke style functions work via message passing. There is a message posted to the UI thread, the message pump will eventually pump this message and convert it to a Marshal'd call.

为了封送标准线程之间的调用,它必须具有某种功能,通过该功能可以检测到要发生的封送调用,然后使该调用发生.这通常是通过某种形式的消息传递来完成的.

In order to marshal a call between a standard thread, it must have some capability by which it can detect a marshal call wants to happen and then make that call happen. This is typically done by message passing of some sort.

IMHO,最标准的方法是通过线程实现,提供并安装SynchronizationContext.这是在线程之间定义封送处理机制的更标准的方法.

IMHO, the most standard way of doing this is by having your thread implement, provide and install a SynchronizationContext. This is a more standard way of defining a Marshaling mechanism between threads.

这篇关于手动编组到线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆