gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:56 28 4
gpt4 key购买 nike

基本例子大家都看过了:

private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}

但是,作为 WPF 和 MVVM 的初学者,我还没有找到实际示例,其中 PropertyChanged 事件:
1. 为null
2. 被另一个线程更改

谁能给我一个同时发生的实际例子?

最佳答案

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

项目符号 2(线程)的一个(稍微少一些?)实际示例可能是第二个单元测试 (Test2) 同时运行 在不同的线程中作为上面的 Test1。第二个测试确实在 Test1 无意中触发事件之前的某个时间订阅了事件,但随后在 if 测试中间再次取消订阅:

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));
}
}

关于c# - PropertyChanged - null 和/或被另一个线程更改 - 实际示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22268999/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com