简体   繁体   English

使用C#任务,在检查之前需要Wait().Result?

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

Written inside a non- async method , is there any difference between this code... 写在非async方法中 ,这段代码有什么区别......

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? 说第二个片段不会阻止正在执行的线程( async方法调用MyMethodAsync() ),而第一个片段是否正确?

Yes the net result is the same: If you wade through that, eventually it may call InternalWait . 是的,最终结果是相同的:如果你跋涉,最终它可能会调用InternalWait

http://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Future.cs,e1c63c9e90fb2f26 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? 说第二个片段不会阻止正在执行的线程(非同步方法调用MyMethodAsync()),而第一个片段是否正确?

Any Task object that calls the Wait or Result is blocking the executing thread. 任何调用Wait或Result的Task对象都会阻塞正在执行的线程。 It is actually not advisable to use Wait or Result because it MIGHT introduce deadlocks to your application. 实际上不建议使用Wait或Result,因为它可能会给你的应用程序带来死锁。

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

Read more on best practices of using async await. 阅读有关使用异步等待的最佳实践的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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