简体   繁体   English

从任务更新GUI

[英]Update GUI from Task

I'm trying to create a method that will encapsulate all GUI operations from a different thread, however when I use it nothing happens and no exception is thrown. 我正在尝试创建一种方法,该方法将封装来自不同线程的所有GUI操作,但是当我使用它时,什么也不会发生,并且不会引发异常。
This is what I got: 这就是我得到的:

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

This line 这条线

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

Compiles to the overload public TResult Invoke<TResult>(Func<TResult> callback); 编译为重载public TResult Invoke<TResult>(Func<TResult> callback);

Your code is executing a Func<Action> which just returns the action, not executing it. 您的代码正在执行Func<Action> ,该Func<Action>仅返回该动作,而不执行它。

What you need is this 你需要的是这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM