Search code examples
.netwpfparallel-processingtask-parallel-librarydispatcher

How to update a WPF Control from the TPL Task?


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 ?
            }
        }
    }

Thank you!


Solution

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

    For example:

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