让我说这个类有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
,因为该属性已从另一个线程更改。如何处理这种奇怪的行为?在属性的setter中使用RaisePropertyChanged()
的MVVM Light执行此操作可以正常工作。
答案 0 :(得分:1)
这是PostSharp的设计结果。问题是由方面TaskStart
检测的方法[NotifyPropertyChanged]
最终会刷新事件队列,但此方法永远不会结束。
这将在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 );
}
}
}