调度员不派遣

时间:2013-06-11 10:04:43

标签: c# wpf task dispatcher

我想测试一些东西,所以我构建了一个小视图&带有Button和ListBox的viewmodel。 当我单击按钮时,我运行RunCommand,如下面的代码所示。我不明白为什么Dispatcher不会触发我希望它运行的动作。

以下是viewmodel代码:

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");
    }
}

任何想法都会很棒

由于

1 个答案:

答案 0 :(得分:2)

  

Dispatcher.CurrentDispatcher - 获取线程的Dispatcher   当前正在执行并创建一个新的Dispatcher(如果还没有)   与线程相关联。

由于您使用了Task.Factory.StartNew,执行此操作的线程不是主线程。 如果要将Dispatcher用于UI线程,则必须使用App.Current.Dispatcher

相关问题