Reputation: 322
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?
Upvotes: 1
Views: 772
Reputation: 43464
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.
Upvotes: 1
Reputation: 1613
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
Upvotes: 1