Sometimes we need to perform a task in the background, but then we want to update the UI when it is completed.
We can make use of a Task and the ContinueWith method so that we can chain tasks together. To ensure that a task is performed on a specific thread, we specify which TaskSheduler to use. To get the UI thread scheduler, we can use TaskScheduler.FromCurrentSynchronizationContext() when we are on the UI thread:
If we are going to run a background task:
var uiThread = TaskScheduler.FromCurrentSynchronizationContext();
Task.Run(() => {
// do some work on a background thread
}).ContinueWith(task => {
// do some work on the UI thread
}, uiThread);
If we need to carry a result from the previous background task:
var uiThread = TaskScheduler.FromCurrentSynchronizationContext();
Task.Run(() => {
// do some work on a background thread
// return a value for the next task
return true;
}).ContinueWith(task => {
// do some work on the UI thread
if (task.Result) {
// make use of the result from the previous task
}
}, uiThread));
