Task continuation on UI thread

Greg Sansom picture Greg Sansom · Dec 2, 2010 · Viewed 99.6k times · Source

Is there a 'standard' way to specify that a task continuation should run on the thread from which the initial task was created?

Currently I have the code below - it is working but keeping track of the dispatcher and creating a second Action seems like unnecessary overhead.

dispatcher = Dispatcher.CurrentDispatcher;
Task task = Task.Factory.StartNew(() =>
{
    DoLongRunningWork();
});

Task UITask= task.ContinueWith(() =>
{
    dispatcher.Invoke(new Action(() =>
    {
        this.TextBlock1.Text = "Complete"; 
    }
});

Answer

Greg Sansom picture Greg Sansom · Dec 2, 2010

Call the continuation with TaskScheduler.FromCurrentSynchronizationContext():

    Task UITask= task.ContinueWith(() =>
    {
     this.TextBlock1.Text = "Complete"; 
    }, TaskScheduler.FromCurrentSynchronizationContext());

This is suitable only if the current execution context is on the UI thread.