Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I await Task.WhenAll( ... ).ContinueWith( AnotherAwaitable )?

I have the following bit of code -

await Task.WhenAll(TaskList /*List of Task objects*/);
await AnotherAwaitableMethod( );

This works fine and is necessary as AnotherAwaitableMethod relies on making certain that a task within TaskList is complete before executing.

However, I would like to be able to say something like

await Task.WhenAll(TaskList).ContinueWith( /*AnotherAwaitableMethod call?*/ );

Is this possible? Am I misunderstanding the purpose of Task.ContinueWith?

like image 635
Will Avatar asked Jul 23 '15 02:07

Will


People also ask

What does await task WhenAll () do?

WhenAll(IEnumerable<Task>)Creates a task that will complete when all of the Task objects in an enumerable collection have completed.

How does task WhenAll work?

WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.

What happens if you dont await a task?

If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.

Does await create a new task C#?

No, async await is just made to allow code to run whilst something else is blocking, and it doesn't do Task.


1 Answers

  await Task.WhenAll(TaskList /*List of Task objects*/);
  await AnotherAwaitableMethod( );

and

 await Task.WhenAll(TaskList /*List of Task objects*/).ContinueWith(_ => {AnotherAwaitableMethod();}).Unwrap();

will act almost identically. Using ContinueWith however will give you a lot move power if you use its overloads. One of the main reasons to use ContinueWith is when you want to execute AnotherAwaitableMethod conditionally based on the result of the first task(s) or when you want to control the context using TaskContinuationOptions

like image 61
KnightFox Avatar answered Oct 25 '22 12:10

KnightFox