问题描述
我发现.NET事件模型是这样的,我会经常在一个线程中引发一个事件,并在另一个线程监听它。我想知道元帅从后台线程事件到我的UI线程最彻底的方法是什么。
基于社区的建议,我用这个:
//早些时候code
mCoolObject.CoolEvent + =
新CoolObjectEventHandler(mCoolObject_CoolEvent);
// 然后
私人无效mCoolObject_CoolEvent(对象发件人,CoolObjectEventArgs参数)
{
如果(InvokeRequired)
{
CoolObjectEventHandler CB =
新CoolObjectEventHandler(
mCoolObject_CoolEvent);
调用(CB,新的对象[] {发件人,ARGS});
返回;
}
//做我的方法的肮脏的工作在这里
}
一对夫妇的意见:
- 请不要在明确code那样创建简单的委托,除非你是pre-2.0,所以你可以使用:
的BeginInvoke(新的EventHandler< CoolObjectEventArgs>(mCoolObject_CoolEvent)
发件人,
参数);
-
此外,你不需要创建和填充对象数组,因为args参数是PARAMS类型,因此你可以通过在列表中。
-
我可能会倾向于
调用
在的BeginInvoke
,因为后者将导致code被异步调用这可能是也可能不是你追求的,但会做出处理后续异常困难,而不调用EndInvoke会
传播。会发生什么是你的应用程序将最终得到一个TargetInvocationException
代替。
I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is.
Based on the community suggestions, I've used this:
// earlier in the code
mCoolObject.CoolEvent+=
new CoolObjectEventHandler(mCoolObject_CoolEvent);
// then
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
if (InvokeRequired)
{
CoolObjectEventHandler cb =
new CoolObjectEventHandler(
mCoolObject_CoolEvent);
Invoke(cb, new object[] { sender, args });
return;
}
// do the dirty work of my method here
}
A couple of observations:
- Don't create simple delegates explicitly in code like that unless you're pre-2.0 so you could use:
BeginInvoke(new EventHandler<CoolObjectEventArgs>(mCoolObject_CoolEvent),
sender,
args);
Also you don't need to create and populate the object array because the args parameter is a "params" type so you can just pass in the list.
I would probably favor
Invoke
overBeginInvoke
as the latter will result in the code being called asynchronously which may or may not be what you're after but would make handling subsequent exceptions difficult to propagate without a call toEndInvoke
. What would happen is that your app will end up getting aTargetInvocationException
instead.
这篇关于要调用跨线程事件彻底的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!