Assume the following synchronous code:
try
{
Foo();
Bar();
Fubar();
Console.WriteLine(\"All done\");
}
catch(Exception e) // For illustration
You should be able to create a method to combine two tasks, and only start the second if the first succeeds.
public static Task Then(this Task parent, Task next)
{
TaskCompletionSource
you can then chain tasks together:
Task outer = FooAsync()
.Then(BarAsync())
.Then(FubarAsync());
outer.ContinueWith(t => {
if(t.IsFaulted) {
//handle exception
}
});
If your tasks are started immediately you can just wrap them in a Func:
public static Task Then(this Task parent, Func nextFunc)
{
TaskCompletionSource tcs = new TaskCompletionSource();
parent.ContinueWith(pt =>
{
if (pt.IsFaulted)
{
tcs.SetException(pt.Exception.InnerException);
}
else
{
Task next = nextFunc();
next.ContinueWith(nt =>
{
if (nt.IsFaulted)
{
tcs.SetException(nt.Exception.InnerException);
}
else { tcs.SetResult(null); }
});
}
});
return tcs.Task;
}