简体   繁体   English

来自Josh Smith的MVVM示例应用程序的EventHandler问题

[英]Question on EventHandler from Josh Smith's MVVM sample application

The following code is from the MVVM sample by Josh Smith: 以下代码来自Josh Smith的MVVM示例:

/// <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? 那么为什么要创建另一个EventHandler引用呢? Or am I missing something here? 或者我在这里遗漏了什么? Thanks 谢谢

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()". 这样做是为了防止在“if”之后但在“RequestClose()”之前的其他线程中更改RequestClose(例如为null)的可能性。

It makes no difference - you are acting on the same event reference in both cases. 它没有任何区别 - 在两种情况下,您都在使用相同的事件引用。 I prefer your commented code. 我更喜欢你评论的代码。

Enjoy! 请享用!

The RequestClose may be set to null or to another object, possibly by another thread since that is an instance variable. RequestClose可能被设置为null或另一个对象,可能是另一个线程,因为它是一个实例变量。 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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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