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";
}
});
I just wanted to add this version because this is such a useful thread and I think this is a very simple implementation. I have used this multiple times in various types if multithreaded application:
Call the continuation with
TaskScheduler.FromCurrentSynchronizationContext()
:This is suitable only if the current execution context is on the UI thread.
With async you just do:
However:
If you have a return value you need to send to the UI you can use the generic version like this:
This is being called from an MVVM ViewModel in my case.
Just write your code as(But using
ContinueWith
is a good practice, don't worry about unnecessary overhead for runtime )Try Avoiding
TaskScheduler.FromCurrentSynchronizationContext()
as from using this your UIThread
can be blocked by your currentThread
.