1

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.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96

1 Answers1

1

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.

usr
  • 168,620
  • 35
  • 240
  • 369
  • In Qt this goes through the event loop. The signal is dispatched to the correct thread later on. There's no interruption of running code involved. I guess the answer is "not possible in C#"? – Nikos C. Oct 12 '14 at 12:59
  • I don't think Qt will ever interrupt a running thread. It might queue a message or an event but never will running code be interrupted. This is even more impossible with C++ than with C#. – usr Oct 12 '14 at 13:05