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

后端 未结 2 1967
温柔的废话
温柔的废话 2020-12-05 16:51

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 m

2条回答
  •  抹茶落季
    2020-12-05 17:38

    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.

提交回复
热议问题