Application.Dispatcher和Window.Dispatcher之间的区别……?
让我介绍一下我对WPF并不是全新的,但是今天我发现了一些我不知道它是如何工作的东西,我简要介绍了我的工作。
我正在编写一个C#WPF代码,我需要根据某些条件填充ObservableCollection
并在UI中显示内容,所以在ViewModel
我启动了一个BackgroundWorker
线程
BackgroundWorker bgwRoot = new BackgroundWorker(); bgwRoot.DoWork += bgwRoot_DoWork(filepath); bgwRoot.RunWorkerAsync(); bgwRoot.RunWorkerCompleted += bgwRoot_RunWorkerCompleted;
线程将继续更新可观察集合,并在完成所有后完成后,BackgroundWorker完成其工作。
这里我想指出FilesCollections = new ObservableCollection();
在MainThread
创建
所以在bgwRoot_DoWork()
中无法直接更新ObservableCollection
我可以理解。 所以我使用了BeginInvoke
Application.Current.Dispatcher.BeginInvoke(new Action(() => this.FilesCollections.Add(myItem)));
但是在调试时我发现Application.Current对象为null
。 最后作为解决方案,我从codeBehind传递Window对象并解决了这个问题。 解决方案是
-
创建Window类的对象
public pUserControl userControl;
-
并在
ViewModel
实例化它userControl = pUserControl;
-
最后
userControl.Dispatcher.BeginInvoke(new Action(() =>
this.FilesCollections.Add(myItem)));
所以我的问题是什么时候我将使用Application.Current.Dispatcher
? 在什么情况下它实际上解决了线程问题? 因为如果我在ViewModel中编写代码来更新任何Collections
并在UI中保留progressbar
,那么VM就没有任何关于View
Object的知识。
那么何时使用Application.Current.Dispatcher.beginInvoke()
? 何时使用userControl.Dispatcher.BeginInvoke()
?
请帮忙。