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(...);
精彩评论