I have a class where each method execute asynchronously, i.e. return a Task, but where each method should nevertheless wait for the completion of the preceding call.
Continuation, right?
Except that a task continuation takes a delegate (Action) in parameter, not another task.
I've tried different things and the best I could do to make it work is the following (to me quite complex) code:
private Task QueueTask(Func<Task> futureTask)
{
var completionSource = new TaskCompletionSource<int>();
_lastTask.ContinueWith(async t =>
{
try
{
await futureTask();
completionSource.SetResult(0);
}
catch (Exception ex)
{
completionSource.SetException(ex);
}
});
_lastTask = completionSource.Task;
return _lastTask;
}
Here _lastTask is a private member of my class. Since all calls are coming from the UI thread, I just keep the last task and put continuation on it.
As I said I find this code quite convoluted. Do you have a better suggestion?