Currently I have a code like this:
bool task1Result = await RunTask1(data);
if(!task1Result)
return false;
bool task2Result = await RunTask2(data);
if(!task2Result)
return false;
bool task3Result = await RunTask3(data);
if(!task3Result)
return false;
bool task4Result = await RunTask4(data);
if(!task4Result)
return false;
Added sample:
private async Task<bool> RunListOfTasks() {
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
var tasks = new List<Task<bool>> { RunTask1(data, ct), RunTask2(data, ct), RunTask3(data, ct), RunTask4(data, ct) };
while (tasks.Any())
{
var currentTask = await Task.WhenAny(tasks);
if (!await currentTask)
{
ct.Cancel();
return false;
}
tasks.Remove(currentTask);
}
return true;
}
Is it possible to run all of them in parallel and if one of them fails (like result is false), then stop processing the rest and return. Thanks
CancellationToken. Then you could useTask.WhenAllto parallelise.CancellationTokenparameter and check it to see if cancellation was signalledif one of them fails (like result is false),that's not whatfailmeans. Afalseresult means the task succeeded and returnedfalse. Failure means that an exception was thrown. You can catch any failure easily if you use a try block aroundawait Task.WhenAll();and signal the other methods to cancel through aCancellationTokenSource. It's a lot harder to do the same if you have to check every result. You won't be able to useTask.WhenAllin that caseboolinstead of throwing? It matters. If they have to return a boolean, you should probably pass aCancellationTokenSourceto each of them, to allow each task to signal cancellation before returning. Typically, cancellation flows from the outside in