Should a keyword be added to C# for raising events?

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, eg

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.


Is it really that error-prone or confusing? Even if they did add such a keyword, they'd still have to keep the old way of raising events for compatibility and you'd have to know the right way to raise the event. You can create an extension method like the following to do most of the work:

public static void Raise(this EventHandler handler, object sender, EventArgs args)
{
  if (handler != null)
  {
    handler(sender, args); 
  }
}

I'd rather see the compiler team work on making the impossible possible than reducing my code base by a few lines.

链接地址: http://www.djcxy.com/p/52936.html

上一篇: JavaScript变量:var a =(3,4,7);

下一篇: 应该将关键字添加到C#中以提升事件吗?