I am trying to chain Task<T>
objects in C# as done in JavaScript and without blocking the UI thread.
I see there is a similar question here, but it uses the non-generic Task
object as a return type of the process functions. I try to do the same with Task<T>
.
I also see that here is a closer question to my needs, but the accepted answer seems to use .Result
twice, which I guess will block the UI thread. Also, note that I chain tasks dynamically, so I can't follow some easy workarounds. And also, the Then
implementation given here seems synchronous too (I am not sure if simply changing the TaskContinuationOptions
on this old sample code will do what I want).
Here is what I have right now, but I can't even make it compile without blocking the thread:
// Initial dummy task.
private Task<bool> taskChain = Task.Factory.StartNew<bool>(() => true);
// Chain dynamically on button click.
private async void DoSth_Click(object sender, RoutedEventArgs e)
{
var data = ....;
System.Threading.Tasks.Task<bool> del = async (t) => { return await ConvertAsync(data); };
taskChain = taskChain.ContinueWith<bool>(() => del);
var res = await taskChain;
}
I have tried various different approaches, but I don't see how I can turn Task<T>
to Func<Task<T>, T>
that ContinueWith<bool>()
seems to require (at least without doing some nasty UI thread blocking operation).
I would expect this to be easy, but I don't quite see the solution here... Isn't there a good and easy way to do this?
(Note: I guess I should probably call Unwrap()
after the ContinueWith()
but this seems like a detail at this point...)