Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 654
core Avatar asked Mar 11 '16 19:03

core


2 Answers

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

like image 58
Daniel A. White Avatar answered Sep 28 '22 12:09

Daniel A. White


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.

like image 43
Jay Avatar answered Sep 28 '22 11:09

Jay