c# - 调度员不调度

标签 c# wpf task dispatcher

我想测试一些东西,所以我用按钮和列表框构建了一个小 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/

相关文章:

c# - 用作变量的类型

c# - 如何从工作线程中调用 UI 线程上的方法?

c# - 属性未在文本框中更新 - WPF

C# Task.Run 在进行多次迭代时跳过值,缺少数据

c# - MemoryStream 的 byte[] 缓冲区可以有可变大小吗?

c# - Unity 如何在检查器中删除数组中的元素标签(Element 0 - Element ...)

wpf - 在MVVM中创建 “lookless” View

c# - CancellationTokenSource.CancelAfter 不工作

mysql - Laravel-我需要帮助将 user_id 传递给 SQL 数据库中的 tasks_table 错误:调用未定义的方法 App\\User::id()

c# - Dynamics CRM 2011 - 找不到插件类型