我想测试一些东西,所以我用按钮和列表框构建了一个小 View 和 View 模型。 当我单击按钮时,我运行 RunCommand,如下面的代码所示。我不明白为什么调度程序不触发我希望它运行的操作。
这是 View 模型代码:
public class ViewModel
{
private ObservableCollection<string> _items = new ObservableCollection<string>();
private ICommand _runCommand;
public ICommand RunCommand { get { return _runCommand ?? (_runCommand = new ActionCommand(RunCommandAction)); } }
private void RunCommandAction()
{
Task.Factory.StartNew(() =>
{
if (Thread.CurrentThread == EnvironmentData.UIThread)
_items.Add("Eldad");
else
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => _items.Add("Eldad")));
});
}
public IEnumerable<string> Items
{
get { return _items; }
}
public ViewModel()
{
_items.Add("Shahar");
}
}
任何想法都会很棒
谢谢
最佳答案
Dispatcher.CurrentDispatcher - Gets the Dispatcher for the thread currently executing and creates a new Dispatcher if one is not already associated with the thread.
由于您使用了 Task.Factory.StartNew ,因此执行此操作的线程不是主线程。 如果你想为 UI 线程使用 Dispatcher,你必须使用 App.Current.Dispatcher
关于c# - 调度员不调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17041498/