3

The following code is from the MVVM sample by Josh Smith:

/// <summary>
/// Raised when this workspace should be removed from the UI.
/// </summary>
public event EventHandler RequestClose;

void OnRequestClose()
{
    //if (RequestClose != null)
    //        RequestClose(this, EventArgs.Empty);
    EventHandler handler = this.RequestClose;
    if (handler != null)
        handler(this, EventArgs.Empty);
 }

The commented lines are my addition. My question is the commented lines would do the same thing as the uncommented lines right? So why create another EventHandler reference? Or am I missing something here? Thanks

Aishwar
  • 9,284
  • 10
  • 59
  • 80
  • 1
    To prevent problem with multiple threads trying to register or unregister the event – Tanmoy Sep 21 '10 at 04:10
  • Can you please elaborate or provide a link for further reading? I don't see how creating another reference to the same object mitigates that problem. – Aishwar Sep 21 '10 at 04:17
  • How exactly does that help? Do you have any reference or something for that? I don't see anything that would help with multiple threads except a pretty minor delay caused by the assignment. – Maxem Sep 21 '10 at 04:19
  • 1
    http://stackoverflow.com/questions/672638/use-of-null-check-in-event-handler/672666#672666 – Tanmoy Sep 21 '10 at 04:27
  • +1 Thanks for the link Tanmoy, if you post an answer I can upvote it too :) – Aishwar Sep 22 '10 at 01:14

3 Answers3

4

Tanmoy is right. This is done to prevent possibility of RequestClose being changed (to null, for example) in other thread after your "if" but before your "RequestClose()".

Dima Stefantsov
  • 943
  • 1
  • 14
  • 20
1

It makes no difference - you are acting on the same event reference in both cases. I prefer your commented code.

Enjoy!

Doug
  • 5,268
  • 24
  • 31
1

The RequestClose may be set to null or to another object, possibly by another thread since that is an instance variable. Assigning the value to a local variable means that you will always have a reference to the event and it can't be changed by other threads. Hope this helps.

Michael Detras
  • 211
  • 2
  • 5