It is possible to execute the following code from multiple threads simultaneously.
this._sequencer.Completed += OnActivityFinished;
Is it thread safe to add delegate to an event handler from multiple threads?
Is it thread safe to remove delegate to from event handler from multiple threads?
What is the simplest and maintainable way of making this thread safe?
If you don’t specify your own event add/remove handlers, the C# compiler generates this add handler (reconstructed by .NET Reflector):
and a remove handler that looks the same but with
Delegate.Removeinstead ofDelegate.Combine.Notice the use of
Interlocked.CompareExchange? This prevents a race condition between updating the event’s backing field and reading from it. Thus, it is thread-safe.