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.
private static void taskContinueWithExploration()
TaskScheduler mTaskSceduler = TaskScheduler.FromCurrentSynchronizationContext();
}).ContinueWith(tsk => txtRaiting.Content = tsk.Result, mTaskSceduler);
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) able to print to the UI.