我有这样的命令:
CancelCommand = new DelegateCommand(Cancel, () => IsProcessing).ObservesProperty(() => IsProcessing);
然后用另一种方法
Task.Factory.StartNew(() =>
{
IsProcessing = true; // Stop here
IsProcessing = false;
});
设置为时,执行会IsProcessing
以某种方式停止true
。但是当我改变为
Application.Current.Dispatcher.Invoke(() => IsProcessing = true);
IsProcessing = false; // Hit this line then stop again
int i = 0; // Never reach here
在非UI线程中设置时,看起来ObservesProperty
会引起问题IsProcessing
。是bug还是按设计工作?
这个问题不是Prism独有的。所有Prism都将其连接到INotifyPropertyChanged
您指定的属性并调用CanExecuteChanged
事件。
该事件ICommand.CanExecuteChanged
可能导致UI元素发生更改(例如更改按钮IsEnabled
属性的值)-因此必须从UI线程中调用它。与绑定引擎不同,它不会自动执行此操作。
您应该:
在启动线程之前/之后,从UI线程设置属性。使用async / await会很容易:
async Task DoStuff() // start this method from the UI thread
{
IsProcessing = true;
try
{
await Task.Run(() => { ... });
}
finally
{
IsProcessing = false;
}
}
使用Dispatcher.InvokeAsync
。千万不能使用Invoke
-那只是浪费了UI,完成一个线程等待。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句