我可以将BeginInvoke与MulticastDelegate一起使用吗? [英] Can I use BeginInvoke with a MulticastDelegate?

查看:83
本文介绍了我可以将BeginInvoke与MulticastDelegate一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的库类中引发一系列事件,但是我担心某些事件订阅者会很粗鲁,并且需要很长时间来处理某些事件,从而阻塞了引发事件的线程.我以为可以通过使用线程池线程引发每个事件来保护上升线程:

I want to raise a series of events from my library class, but I'm worried that some event subscribers will be rude and take a long time to process some events, thus blocking the thread that is raising the events. I thought I could protect the raising thread by using a thread pool thread to raise each event:

if (packet != null && DataPacketReceived != null)
{
    var args = new DataPacketEventArgs(packet);
    DataPacketReceived.BeginInvoke(this, args, null, null);
}

当事件只有一个订阅者时,这很好用,但是当第二个订阅者到达时,DataPacketReceived成为多播委托,并且我收到带有错误消息的参数异常,该委托必须只有一个目标."是否有一种简单的方法可以在单独的线程上引发事件,还是我必须启动一个线程然后从那里引发事件?

That works fine when there's only one subscriber to the event, but as soon as a second subscriber arrives, DataPacketReceived becomes a multicast delegate, and I get an argument exception with the error message, "The delegate must have only one target." Is there an easy way to raise the event on a separate thread, or do I have to start a thread and then raise the event from there?

推荐答案

我在另一个站点,当然,乔恩·斯凯特(Jon Skeet)也回答了.对于我的情况,我选择在单独的线程上引发每个订户的事件:

I found a similar question on another site, and of course Jon Skeet had answered it. For my scenario, I chose to raise the event for each subscriber on a separate thread:

if (packet != null && DataPacketReceived != null)
{
    var args = new DataPacketEventArgs(packet);
    var receivers = DataPacketReceived.GetInvocationList();
    foreach (EventHandler<DataPacketEventArgs> receiver in receivers)
    {
        receiver.BeginInvoke(this, args, null, null);
    }
}

这篇关于我可以将BeginInvoke与MulticastDelegate一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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