Raising events in thread-safe way (in order to avoid NullReferenceException
) requires copying the event delegate before calling it:
EventHandler copy = TheEvent;
if (copy != null)
copy(this, EventArgs.Empty);
or using the null-conditional operator and Volatile.Read
in C# 6 as proposed by Jon Skeet:
Volatile.Read(ref TheEvent)?.Invoke(this, EventArgs.Empty);
(See C# Events and Thread Safety for the discussion).
This is tedious and error-prone. Would it not make sense to add a raise
keyword to C# so that the above pattern (or an improved one chosen by the C# compiler team) would be taken care of transpararently by the compiler, e.g.
raise TheEvent(this, EventArgs.Empty);
This would be a syntactic convenience in line with using
and async
/await
that would solve the confusion around the proper way of raising events in a conclusive way.
What are the downsides?
EDIT
Thanks to all of you for the feedback - adding another keyword is indeed a bit extreme.
However, as the "standard" way of raising events is still lacking and as many people like the Raise()
extension method, I proposed to add it to mscorlib
at the Visual Studio UserVoice channel.