我有这样的命令:
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
当 IsProcessing
设置在非 UI 线程中时,看起来 ObservesProperty
会导致问题。它是错误还是按设计工作?
最佳答案
这个问题不是 Prism 独有的。所有 Prism 都会连接到您指定的属性的 INotifyPropertyChanged
并调用 CanExecuteChanged
事件。
ICommand.CanExecuteChanged
事件可能会导致 UI 元素发生变化(例如更改按钮的 IsEnabled
属性的值)- 因此必须从 UI 线程调用它.与绑定(bind)引擎不同,它不会自动执行此操作。
你应该:
在启动线程之前/之后从 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 完成。
关于c# - 使用 ObservesProperty 的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38501960/