如何更新一个WPF控件从TPL任务? [英] How to update a WPF Control from the TPL Task?

查看:188
本文介绍了如何更新一个WPF控件从TPL任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更新一个WPF控件从TPL任务?

How to update a WPF Control from the TPL Task?

细,所以我尝试了一些场景来使用调度但无论如何,它给人的错误。我需要帮助的人!

Fine so I tried some scenarios to use Dispatcher but anyway it gives the error. I need help guys!

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        //Application.Current.Dispatcher.Invoke((Action)MyInit); 
        backgroundDBTask = Task.Factory.StartNew(() =>
            {
                DoSomething1();
            }, TaskCreationOptions.LongRunning);
        backgroundDBTask.ContinueWith((t) =>
        {
            // ... UI update work here ...
        },             
        TaskScheduler.FromCurrentSynchronizationContext());             
    }

    void DoSomething1()
    {
        // MyInit();
        int number = 0;
        while (true)
        {
            if (state)
            {
                Thread.Sleep(1000);
                Console.WriteLine("Begin second task... {0}", number++);
               // mostCommonWords = GetMostCommonWords(words) + string.Format("   Begin second task... {0}", number++);

                textBox2.Text = (number++).ToString(); // Gives the error

                Dispatcher.BeginInvoke(); // How it should be ?
            }
        }
    }

感谢您!

推荐答案

您需要传递一个委托,做你的工作,以的BeginInvoke
的BeginInvoke 将异步运行此委托在UI线程上。

You need to pass a delegate that does your work to BeginInvoke.
BeginInvoke will asynchronously run this delegate on the UI thread.

例如:

Dispatcher.BeginInvoke(new Action(delegate {
    textBox2.Text = number.ToString(); 
}));

这篇关于如何更新一个WPF控件从TPL任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆