简体   繁体   English

如何在订阅者的线程上调用事件处理程序?

[英]How do I call event handlers on the threads of the subscribers?

In my C++/Qt applications, whenever I want to raise a signal/event, I would simply do: 在我的C ++ / Qt应用程序中,每当我想引发信号/事件时,我都会简单地执行以下操作:

emit Event();

This would call all handlers for Event() on the same thread as the objects that subscribed to this event. 这将在与预订此事件的对象相同的线程上调用Event()所有处理程序。

C# doesn't seem to offer anything like that, so how do I do this? C#似乎没有提供类似的功能,那么我该怎么做呢?

I have a class, let's call it EventRaiser , which has a SomethingHappened event and a method that raises the event when needed: 我有一个类,我们将其EventRaiser ,它具有SomethingHappened事件和在需要时引发事件的方法:

class EventRaiser
{
    public event EventHandler SomethingHappened;

    void RaiseEvent()
    {
        var anyoneWhosInterested = SomethingHappened;
        if (anyoneWhosInterested != null)
        {
            try { anyoneWhosInterested(this, new EventArgs()); }
            catch { /* we don't care */ }
        }
    }
}

My problem is that RaiseEvent() will call the handlers on the thread RaiseEvent() got called. 我的问题是RaiseEvent()会在被调用的线程RaiseEvent()上调用处理程序。 But I need to call the handlers on the threads that subscribed to the event. 但是我需要在订阅该事件的线程上调用处理程序。

How do I do this? 我该怎么做呢?

I'm on .NET 2.0 and Visual Studio 2012. 我在.NET 2.0和Visual Studio 2012上。

In general this idea does not make sense because you can't arbitrarily interrupt running code on a different thread and inject an event. 通常,这种想法没有任何意义,因为您不能随意中断另一个线程上的运行代码并注入事件。 That architecture would cause high amounts of random breakage. 该架构将导致大量的随机破坏。

Make the subscribers handle the synchronization and marshaling. 使订户处理同步和封送处理。 They know what thread they are running on and how to safely marshal a call onto it. 他们知道正在运行的线程,以及如何安全地对其进行封送处理。

Consider capturing the current SynchronizationContext in the SomethingHappened.add handler and sending/posting the event to that SynchronizationContext . 考虑在SomethingHappened.add处理程序中捕获当前的SynchronizationContext并将事件发送/发布到该SynchronizationContext This only works if the subscribing thread has a meaningful context. 这仅在订阅线程具有有意义的上下文时才有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM