Nikos C.
Nikos C.

Reputation: 51880

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:

emit Event();

This would call all handlers for Event() on the same thread as the objects that subscribed to this event.

C# doesn't seem to offer anything like that, so how do I do this?

I have a class, let's call it EventRaiser, which has a SomethingHappened event and a method that raises the event when needed:

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. 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.

Upvotes: 1

Views: 276

Answers (1)

usr
usr

Reputation: 171206

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. This only works if the subscribing thread has a meaningful context.

Upvotes: 1

Related Questions