我可以将 BeginInvoke 与 MulticastDelegate 一起使用吗?
我想从我的库类中引发一系列事件,但我担心某些事件订阅者会很粗鲁,需要很长时间来处理某些事件,从而阻塞引发事件的线程。我认为我可以通过使用线程池线程来引发每个事件来保护引发线程:
if (packet != null && DataPacketReceived != null)
{
var args = new DataPacketEventArgs(packet);
DataPacketReceived.BeginInvoke(this, args, null, null);
}
当只有一个事件订阅者时,这种方法工作正常,但一旦第二个订阅者到达,DataPacketReceived
就会变成多播委托,我收到一个参数异常,并显示错误消息“委托必须只有一个目标”。有没有一种简单的方法可以在单独的线程上引发事件,或者我是否必须启动一个线程,然后从那里引发事件?
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);
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在另一个网站< /a>,当然乔恩·斯基特已经回答了。对于我的场景,我选择在单独的线程上为每个订阅者引发事件:
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: