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.
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.
}
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
Updated on August 04, 2022Comments
-
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 over 10 yearsWhat kind of UI do you use? WPF, Windows Forms, Silverlight, Web?
-
Sergey Vyacheslavovich Brunov over 10 years@NightWalker, please see my answer.
-
-
LievenV over 7 yearsThanks, 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 over 7 yearsWord of warning -
Task.Run
is a heavyweight operation, it creates a new thread and gobbles up a lot of stack space. Use sparingly.