我如何获得Task.WaitAll()在一个控制台应用程序返回值?
我使用一个控制台应用程序的概念和新的需要得到一个异步的返回值的证明。
I am using a console app as a proof of concept and new need to get an async return value.
我想通了,我需要使用 Task.WaitAll()
在我的主要方法,以避免需要一个异步的main()方法,这是违法的。
I figured out that I need to use Task.WaitAll()
in my main method to avoid needing an async "main()" method, which is illegal.
我现在卡住试图找出过载,允许我使用泛型或只返回一个对象,我可以投,但在main()。
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().
您没有从 Task.WaitAll
返回值。你只用它来等待多个任务完成后得到任务本身的返回值。
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;
这通常不是一个好主意同步等待(块)上的异步任务(过异步同步),但我想,对于一个POC的罚款。
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.