【问题标题】:Update GUI from Task从任务更新 GUI
【发布时间】:2015-04-12 19:26:30
【问题描述】:

我正在尝试创建一个方法来封装来自不同线程的所有 GUI 操作,但是当我使用它时,什么都没有发生,也没有抛出异常。
这是我得到的:

    private Task t1;
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        t1 = Task.Factory.StartNew(() => DoStuffInTask())
            .ContinueWith(tsk => Finished(tsk));
    }

    private void DoStuffInTask()
    {
        //doing important stuff...
        for (int i = 0; i < Int16.MaxValue; i++)
        {
            //Text is a property that raises INotifyPropertyChanged event
            RunOnGui(() => { Text = i.ToString(); }); // not working, not throwing exception
            Application.Current.Dispatcher.Invoke(() => Text = i.ToString()); // works fine
        }
    }

    private void RunOnGui(Action action)
    {
        Application.Current.Dispatcher.Invoke(() => action);
    }

【问题讨论】:

    标签: c# wpf task-parallel-library .net-4.5


    【解决方案1】:

    这一行

    Application.Current.Dispatcher.Invoke(() => action);
    

    编译为重载public TResult Invoke&lt;TResult&gt;(Func&lt;TResult&gt; callback);

    您的代码正在执行一个Func&lt;Action&gt;,它只是返回操作,而不是执行它。

    你需要的是这个

    private void RunOnGui(Action action)
    {
        Application.Current.Dispatcher.Invoke(action);//Note no lambda here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多