Update UI from task (Task schedulers)

8:00 AM

Sometime we need to update UI from a task. In order to update UI we should run or return result in UI thread. But it seems to impossible since all tasks run on threads provided by ThreadPool.


But still, we can achieve updating UI from the task by using synchronization context Task Scheduler. First we will see an approach and then we will discuss about it and explain what we just saw.

Example:

        private static void taskContinueWithExploration()
        {
            TaskScheduler mTaskSceduler = TaskScheduler.FromCurrentSynchronizationContext();

            Task.Factory.StartNew(() =>
                {
                    Console.WriteLine(makeCalculations);
                }).ContinueWith(tsk => txtRaiting.Content = tsk.Result, mTaskSceduler);
        }

Explanation:

Task Scheduler is a an abstract class that providing thread to the task via Thread Pool. There are two concrete implementations of Task Scheduler:

  • Default Task Scheduler (the regular one)
  • Synchronization Context Task Scheduler (give us ability work with UI)

Regarding the example:

  • This example update WPF text box with result of makeCalculations() method
  • First task (StartNew) making calculations (some long algorithm calculations, working with web service,..)
  • The second task (ContinueWith) will be able to print to the UI thread.


You Might Also Like

0 comments.

Popular Posts

Total Pageviews