简体   繁体   中英

With C# tasks, Wait() necessary before checking .Result?

Written inside a non- async method , is there any difference between this code...

return MyMethodAsync().Result;

...and this, below?

var task = MyMethodAsync();

task.Wait();

return task.Result;

That is to say, is the behavior of those two the identical?

Is it correct to say that the second snippet does not block the executing thread (the non- async method calling MyMethodAsync() ), while the first does?

Yes the net result is the same: If you wade through that, eventually it may call InternalWait .

http://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Future.cs,e1c63c9e90fb2f26

Is it correct to say that the second snippet does not block the executing thread (the non-async method calling MyMethodAsync()), while the first does?

Any Task object that calls the Wait or Result is blocking the executing thread. It is actually not advisable to use Wait or Result because it MIGHT introduce deadlocks to your application.

https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

Read more on best practices of using async await.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM