简体   繁体   中英

What's the difference between following code for adding new events

-- If I define an event with an inital empty delegate I don't need to check for null

class MyClass
{
 public event EventHandler<MyEventArgs> MyEvent = delegate { };

 void SomeMethod()
 {
  ...
  MyEvent(); // No need to check for null
  ...
 }
}

-- Otherwise I need to check for null

class MyClass
{
 public event EventHandler<MyEventArgs> MyEvent;

 void SomeMethod()
 {
  ...
  if (MyEvent != null) // No need to check for null
   MyEvent(); 
  ...
 }
}

What's the difference between these? In what cases one is better than another?

Thanks

The upvoted answer is dramatically wrong, I have to post an answer. Somebody is wrong on the Internet, can't come to bed just yet.

It is convenient but it doesn't come for free. The compiler has to generate a class for the anonymous method and the JIT compiler has to generate code for it. And that code always executes when you raise the event, whether or not a client has subscribed an event handler. The null check code also always executes, but that takes a lot less code and time.

This isn't a lot of code and a lot of time. The null check takes 2 machine code instructions and should execute in a single CPU cycle. The anonymous delegate takes about an order of magnitude more but that's still not a lot on a modern machine. Personally, I'm too old to be wasteful like that, two invariably is my choice.

Not in the least because that's the standard pattern, everybody recognizes it.

First one is applicable solution, but it has very very little performance penalty to call extra empty delegate.

Second solution is not thread safe (if it matters for you, of cause).

You should use following:

var handler = MyEvent;
if (handler != null )
  handler(this, new MyEventArgs());

At our company we wrote an extension method which hooks onto most events, and checks if it's null before invoking.

We reduced this:

var handler = MyEvent;
if (handler != null)
{
    handler(...);
}

to

MyEvent.SafeTrigger(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM