我可以将 BeginInvoke 与 MulticastDelegate 一起使用吗?

发布于 2024-10-12 09:44:09 字数 452 浏览 4 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱给你人给你 2024-10-19 09:44:09

我在另一个网站< /a>,当然乔恩·斯基特已经回答了。对于我的场景,我选择在单独的线程上为每个订阅者引发事件:

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);
    }
}

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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文