调用跨线程事件的最简洁方法 [英] Cleanest Way to Invoke Cross-Thread Events

查看:30
本文介绍了调用跨线程事件的最简洁方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 .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 over BeginInvoke 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 to EndInvoke. What would happen is that your app will end up getting a TargetInvocationException instead.

      这篇关于调用跨线程事件的最简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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