Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

c# - 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().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...