Question on EventHandler from Josh Smith's MVVM sample application

巧了我就是萌 提交于 2020-01-04 02:40:33

问题


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


回答1:


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()".




回答2:


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

Enjoy!




回答3:


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.



来源:https://stackoverflow.com/questions/3757234/question-on-eventhandler-from-josh-smiths-mvvm-sample-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!