是NotifyPropertyChanged线程安全的? [英] Is NotifyPropertyChanged thread safe?

查看:111
本文介绍了是NotifyPropertyChanged线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看 NotifyPropertyChanged() INotifyPropertyChanged的,并注意到,在微软的例子,如在这里:

I am looking at NotifyPropertyChanged() from INotifyPropertyChanged and noticed that in the examples from Microsoft such as here:

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

有没有委托基准捕获第一次(因为它说要在这里做的,例如:在事件处理程序无效支票使用

There is no capturing of the delegate reference first (as it says to do here for example: Use of null check in event handler)

我在自动生成Reference.cs我ServiceReferences一看,这个检查已经完成。

I had a look in the auto-generated Reference.cs for my ServiceReferences and this check is done.

所以我的问题是我应该这样做(无论以何种形式,如扩展方法等)?是否有任何可能的问题,如果我不?

So my question is should I be doing this (in whatever form such as extension methods etc)? Are there any possible issues if I don't?

推荐答案

您说得对,检查应该做他们的榜样是错了。

You're right, the check should be done and their example is wrong.

下面是标准的代码。

private void NotifyPropertyChanged(String propertyName)
{
    var handler = PropertyChanged;
    if (handler != null)
    {
        handler (this, new PropertyChangedEventArgs(propertyName));
    }
}



编辑:进一步解释为什么这是需要(以及为什么它的工作原理)

A further explanation about why this is needed (and why it works)

在MS的例子,他们直接做一个空检查上的PropertyChanged,然后调用它。这样将有可能对于的PropertyChanged成为空检查和调用之间空。通过分配委托给一个局部变量,我们可以确保我们保留委托一个参考,它不能空支票和调用之间切换。

In the MS example they do a null check directly on PropertyChanged and then invoke it. So it would be possible for PropertyChanged to become null between the null check and the invocation. By assigning the delegate to a local variable, we can ensure that we retain a reference to the delegate and it can't change between the null check and invocation.

这篇关于是NotifyPropertyChanged线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆