In the context of a C# console application, if I make a loop used to receive message asynchronously which raises an event for each message received, such as :
while (true)
{
var message = await ReceiveMessageAsync();
ReceivedMessage(new ReceivedMessageEventArgs(message));
}
Now if I have multiple subscribers to the event (let’s say 3 subscribers for the sake of the example), all of them using an asynchronous event handler such as :
async void OnReceivedMessageAsync(object sender, ReceivedMessageEventArgs args)
{
await TreatMessageAsync(args.Message);
}
Should message object be coded in a thread safe way ? I think so, as TreatMessageAsync code from the different event handlers may run concurently for all the subscribers (when event is raised, the three async event handlers of the subscribers are called, each launching an async operation which potentially could be run concurently on different threads by the task scheduler). Or am I wrong ?
Thanks !
You should code it in a thread-safe way. The easiest way to do so is to make it immutable.
If you have a true event, then its arguments should be immutable. If you’re using an event handler for something that’s not a true event (like a command or implementation) then you may want to modify your API.
It is possible to have concurrent event handlers because each handler will start sequentially, but they can resume concurrently.