对于C#任务,在检查.Result之前必须先使用Wait()? [英] With C# tasks, Wait() necessary before checking .Result?

查看:94
本文介绍了对于C#任务,在检查.Result之前必须先使用Wait()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

写在非 async 方法中,此代码之间是否有任何区别...

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

return MyMethodAsync().Result;

...下面呢?

var task = MyMethodAsync();

task.Wait();

return task.Result;

也就是说,这两个行为是完全相同的吗?

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

说第二个代码段不会阻塞正在执行的线程(调用 MyMethodAsync() non- async 方法)是否正确?,而第一个呢?

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?

推荐答案

是的,最终结果是相同的:如果您经历了这些,最终它可能会调用 InternalWait .

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

这篇关于对于C#任务,在检查.Result之前必须先使用Wait()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆