C# PropertyChanged-null和/或被另一个线程更改-实际示例?

C# PropertyChanged-null和/或被另一个线程更改-实际示例?,c#,wpf,multithreading,mvvm,C#,Wpf,Multithreading,Mvvm,每个人都看到了基本示例: private void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } 但是,作为WPF和MVVM的

每个人都看到了基本示例

private void RaisePropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
但是,作为WPF和MVVM的初学者,我还没有找到一个实际例子,其中
属性发生了变化
事件:
1.为空

2.被另一个线程更改了


有人能给我一个两者都发生的实例吗?

bullet 1(null)的一个实例可能是,如果您在ViewModel上运行单元测试。在这种情况下,将不会有绑定到ViewModel的UI,如果测试方法(
Test1
)在未订阅
PropertyChanged
事件的情况下更新属性,您将获得
NullReferenceException

bullet 2(线程化)的一个(稍微少一点?)实际示例可能是,如果第二个单元测试(
Test2
)与上面的Test1在不同的线程中同时运行。第二个测试确实在Test1无意中触发事件之前某个时间订阅事件,但是在<代码>中间,如果“< /代码>测试:

”,则再次取消订阅。
private void RaisePropertyChanged(string propertyName)
{
    //1: Test1 changes a property, and triggers this event.
    //   Because Test2 earlier subscribed to the event, PropertyChanged is not null here
    if (PropertyChanged != null)
    {
        //2: Test2 sneaks in from a different thread
        //   and *unsubscribes* from PropertyChanged, making it null again.

        //3: Test1 then gets a NullReferenceException here,
        //   because there's no local "handler" variable that kept the original delegate.
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

可能的重复是相关的,但这不是同一个问题!在第一个问题中编辑,询问与您在此处询问的相同的问题。是否。。。没有人愿意回嘴。。。这是可以理解的:这是另一个问题,它与原始问题不同……在创建/使用视图模型时,并非每个视图模型都必须可视化。如果你改变了主意,不想再去想象什么了,那该怎么办?你的申请应该说明这一点。您不应该关心是否为该视图模型创建了视图或创建了多少视图。同样的规则适用于所有其他事件,而不仅仅是
PropertyChanged
ok。。。所以,测试。。。如果我不测试GUI呢?或者避免对GUI使用多线程?我在某个地方看到过它……而且除了GUI,永远不要使用您的ViewModels。我想您是安全的。毕竟,这是一种安全而不是遗憾的方法。但有一天,您可能想将其中一个ViewModel用作其他项目的帮助器类,您发现自己处于情况1中。因此,您至少应该检查是否为空。除了GUI之外,我为什么还要使用视图模型呢?无论如何,我有了这个想法,我应该把代码放在一个类中,比如
observateObject
,其他视图模型会扩展它。。。