问题描述
我发现 .NET 事件模型是这样的,我经常在一个线程上引发事件并在另一个线程上侦听它.我想知道将事件从后台线程编组到我的 UI 线程的最简洁方法是什么.
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
}
推荐答案
几点意见:
- 不要在这样的代码中显式创建简单的委托,除非您是 2.0 之前的版本,否则您可以使用:
BeginInvoke(new EventHandler<CoolObjectEventArgs>(mCoolObject_CoolEvent),
sender,
args);
此外,您不需要创建和填充对象数组,因为 args 参数是params"类型,因此您只需传入列表即可.
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.
我可能更喜欢
Invoke
而不是BeginInvoke
因为后者会导致代码被异步调用,这可能是也可能不是你想要的,但是如果不调用EndInvoke
,将使得处理后续异常难以传播.会发生的情况是,您的应用最终会收到TargetInvocationException
.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.这篇关于调用跨线程事件的最简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!