How should I update from Task the UI Thread?
Here is a good article: Parallel Programming: Task Schedulers and Synchronization Context.
Take a look at Task.ContinueWith() method.
Example:
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);task.Start();
Since .NET 4.5 supports async
/await
keywords (see also Task.Run vs Task.Factory.StartNew):
try{ var result = await Task.Run(() => GetResult()); // Update UI: success. // Use the result.}catch (Exception ex){ // Update UI: fail. // Use the exception.}
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)
You can use the Dispatcher
to invoke code on UI thread. Take a look at the article Working With The WPF Dispatcher