我可以将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);
}
}