不调用另一个线程中属性更新的 RaisePropertyChanged

RaisePropertyChanged on Porperty updated in another thread is not called

假设我有这个 class 和来自 PostSharp 的 RaiseProperyChanged 属性:

[NotifyPropertyChanged]
public class MainViewModel
{
    public int RandInt { get; set; }

    public MainViewModel()
    {
        RandInt = 10;
        new Task(TaskStart).Start();
    }

    private void TaskStart()
    {
        Random rand = new Random();
        while (true)
        {
            RandInt = rand.Next(9999);
        }
    }
}

RandInt 绑定到标签或其他控件不会导致标签发生变化。这意味着标签的值将一直是 10 因为 属性 是从另一个线程更改的。如何处理这种奇怪的行为?使用 MVVM Light 在 属性 的 setter 中使用 RaisePropertyChanged() 可以正常工作。

这是 PostSharp 的设计结果。问题是方面 [NotifyPropertyChanged] 检测的方法 TaskStart 最后会刷新事件队列,但此方法永远不会结束。

这将在 PostSharp 的未来版本中解决。同时,您可以使用方法NotifyPropertyChangedServices.RaiseEventsImmediate()。看例子:

[NotifyPropertyChanged]
public class MainViewModel
{
    public int RandInt { get; set; }

    public MainViewModel()
    {
        RandInt = 10;
        new Task(TaskStart).Start();
    }

    private void TaskStart()
    {
        Random rand = new Random();
        while (true)
        {
            AsyncRandomNumber = random.Next( 9999 );

            // Raise the events now, because the method TaskStart never ends.
            NotifyPropertyChangedServices.RaiseEventsImmediate( this );
        }
    }
}