1

I am having some confusion regarding events and synchronization. I am working in .Net Core 3.1. I multiple event handlers that need to perform asynchronously from each other, but after doing some research online I am not sure whether or not these operations are asynchronous or not, which they need to be. Can somebody with knowledge on asynchronous operations in C# give me some guidance? Here is the basic set up:

public class ReceiveClass {
    public EventHandler<MyEventArgs> OnReceive;
    public void Receive(object myData) 
    {
         // some processing
         OnReceive?.Invoke(new MyEventArgs { Data = myData });
    }
}

The Receive method may be invoked asynchronously, and the eventhandler may have many listeners. Will the listeners be invoked asynchronously, or synchronously? If synchronously, how can I make it asynchronous?

SA3709
  • 192
  • 2
  • 11
  • What do you mean _"The Receive method may be invoked asynchronously"_? You mean on a non-UI Thread? In a Task.Run? BTW: You can test it. Throw in some logging including the Thread-Ids ... – Fildor Mar 25 '20 at 16:21
  • It is called on a non-UI thread in a Task.Run – SA3709 Mar 25 '20 at 16:26

2 Answers2

1

The .Invoke part will be run synchronously for all the "Subscribers" of the event. If you want on each subscriber to execute something asynchronously, you are free to do so.

But, if for your application require the invoking to be run asynchronously, there is a discussion already in this SO question

Sotiris Panopoulos
  • 1,523
  • 1
  • 13
  • 18
1

If you don't want to be blocked by the event handlers, you can invoke them from a ThreadPool thread, with Task.Run:

public void Receive(object myData) 
{
     // some processing
     var handler = OnReceive;
     if (handler != null)
     {
         var fireAndForget = Task.Run(handler.Invoke(new MyEventArgs { Data = myData }));
     }
}

The implication is that any exceptions thrown by the handlers will remain unobserved.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104