I'm trying to properly start a returned Task on a background thread so as not to block the UI thread.
The blocking call is done in another class as such:
var tcs = new TaskCompletionSource<T>();
request.BeginGetResponse(() => DoSomethingSlowThenCompleteTCS(tcs));
return tcs.Task;
I assumed I could simply start the task as such (or a million other variations I've tried:
CallThatReturnsTask()
.ContinueWith(
x =>
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new System.Action(() =>
{
// Some continuation stuff that needs to be on the dispatcher
}
))).Start();
base.OnActivate(); // Call that needs to run immediately
However I've found that I needed to wrap the returning task in a Task.Run() in order to not block the UI thread. I'm almost 100% certain that doing this defeats the purpose of returning the Task in the first place, but it's the only way I've gotten it working.
Task.Run(() =>
{
CallThatReturnsTask()
.ContinueWith(
x =>
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new System.Action(() =>
{
// Some continuation stuff that needs to be on the dispatcher
}
)));
});
base.OnActivate(); // Call that needs to run immediately
What's the correct way to go about this?
Thanks in advance.
-------------------- Edit 1 --------------------
Is this better? It still seems as if I'm wrapping a task within a task instead of just executing the first task on the correct thread.
Task.Run(() => {
var result = CallThatReturnsTask().Result;
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new System.Action(() =>
{
// Dispatcher stuff
}
));
});