Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a return value from Task.WaitAll() in a console app?

I am using a console app as a proof of concept and new need to get an async return value.

I figured out that I need to use Task.WaitAll() in my main method to avoid needing an async "main()" method, which is illegal.

I'm now stuck trying to figure out an overload that allows me to use generics or just returns an object that I can cast, but while in Main().

like image 228
makerofthings7 Avatar asked Aug 15 '14 00:08

makerofthings7


People also ask

Does Task WaitAll block?

WhenAll we will get a task object that isn't complete. However, it will not block but will allow the program to execute. On the contrary, the Task. WaitAll method call actually blocks and waits for all other tasks to complete.

What is Task<> in. net?

The Task class represents a single operation that does not return a value and that usually executes asynchronously. Task objects are one of the central components of the task-based asynchronous pattern first introduced in the . NET Framework 4.

How does Task work in C#?

A task in C# is used to implement Task-based Asynchronous Programming and was introduced with the . NET Framework 4. The Task object is typically executed asynchronously on a thread pool thread rather than synchronously on the main thread of the application.


2 Answers

You don't get a return value from Task.WaitAll. You only use it to wait for completion of multiple tasks and then get the return value from the tasks themselves.

var task1 = GetAsync(1); var task2 = GetAsync(2); Task.WaitAll(task1, task2); var result1 = task1.Result; var result2 = task2.Result; 

If you only have a single Task, just use the Result property. It will return your value and block the calling thread if the task hasn't finished yet:

var task = GetAsync(3); var result = task.Result; 

It's generally not a good idea to synchronously wait (block) on an asynchronous task ("sync over async"), but I guess that's fine for a POC.

like image 184
i3arnon Avatar answered Sep 28 '22 21:09

i3arnon


For best practice, use the new async way of doing things. Instead of

  • Task.WaitAll use await Task.WhenAll
  • Task.WaitAny use await Task.WhenAny

The code above can be written as:

var task1 = GetAsync(1); var task2 = GetAsync(2); var results = await Task.WhenAll(task1, task2); var result1 = results[0]; var result2 = results[1]; 
like image 36
alltej Avatar answered Sep 28 '22 20:09

alltej