Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - Event handler raising method convention

I was just browsing and came across this question:

Action vs delegate event

The answer from nobug included this code:

protected virtual void OnLeave(EmployeeEventArgs e) {
  var handler = Leave;
  if (handler != null)
    handler(this, e);
}

Resharper also generates similar code when using the "create raising method" quick-fix.

My question is, why is this line necessary?:

var handler = Leave;

Why is it better than writing this?:

protected virtual void OnLeave(EmployeeEventArgs e) {
  if (Leave != null)
    Leave(this, e);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's better because there is a tiny possibility that Leave becomes null after the null check, but before the invocation (which would cause your code to throw a NullReferenceException). Since the delegate type is immutable, if you first assign it to a variable this possibility goes away; your local copy will not be affected by any changes to Leave after the assignment.

Note though that this approach also creates a issue in reverse; it means that there is a (tiny, but existing) possibility that an event handler gets invoked after it has been detached from the event. This scenario should of course be handled gracefully as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...