How should I update from Task the UI Thread?


Solution 1

You need to run the ContinueWith -task on the UI thread. This can be accomplished using the TaskScheduler of the UI thread with the overloaded version of the ContinueWith -method, ie.

TaskScheduler scheduler = TaskScheduler.Current;
...ContinueWith(obj => LogContent = obj.Result), CancellationToken.None, TaskContinuationOptions.None, scheduler)

Solution 2

Here is a good article: Parallel Programming: Task Schedulers and Synchronization Context.

Take a look at Task.ContinueWith() method.


var context = TaskScheduler.FromCurrentSynchronizationContext();
var task = new Task<TResult>(() =>
        TResult r = ...;
        return r;

task.ContinueWith(t =>
        // Update UI (and UI-related data) here: success status.
        // t.Result contains the result.
    CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, context);

task.ContinueWith(t =>
        AggregateException aggregateException = t.Exception;
        aggregateException.Handle(exception => true);
        // Update UI (and UI-related data) here: failed status.
        // t.Exception contains the occured exception.
    CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, context);


Since .NET 4.5 supports async/await keywords (see also Task.Run vs Task.Factory.StartNew):

    var result = await Task.Run(() => GetResult());
    // Update UI: success.
    // Use the result.
catch (Exception ex)
    // Update UI: fail.
    // Use the exception.

Solution 3

You can use the Dispatcher to invoke code on UI thread. Take a look at the article Working With The WPF Dispatcher

Night Walker
Author by

Night Walker

Updated on August 04, 2022


  • Night Walker
    Night Walker 10 months

    I have a task that performing some heavy work. I need to path it's result to LogContent

    Task<Tuple<SupportedComunicationFormats, List<Tuple<TimeSpan, string>>>>.Factory
        .StartNew(() => DoWork(dlg.FileName))
        .ContinueWith(obj => LogContent = obj.Result);

    This is the property:

    public Tuple<SupportedComunicationFormats, List<Tuple<TimeSpan, string>>> LogContent
        get { return _logContent; }
        private set
            _logContent = value;
            if (_logContent != null)
                string entry = string.Format("Recognized {0} log file",_logContent.Item1);
                _traceEntryQueue.AddEntry(Origin.Internal, entry);

    Problem is that _traceEntryQueue is data bound to UI, and of cause I will have exception on code like this.

    So, my question is how to make it work correctly?

    • Alexander Schmidt
      Alexander Schmidt over 10 years
      What kind of UI do you use? WPF, Windows Forms, Silverlight, Web?
    • Sergey Vyacheslavovich Brunov
      Sergey Vyacheslavovich Brunov over 10 years
      @NightWalker, please see my answer.
  • LievenV
    LievenV over 7 years
    Thanks, this was exactly what I was trying to achieve. A simple way to run a method async but still be able to update the main thread. I played around with Await Task.Run() but got nothing.
  • Contango
    Contango over 7 years
    Word of warning - Task.Run is a heavyweight operation, it creates a new thread and gobbles up a lot of stack space. Use sparingly.