在异步返回类型 [英] On async return type

查看:57
本文介绍了在异步返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道为什么我们应该指定async方法确实返回Task对象.

Wondering why we should specify that async method does return Task object.

使用async关键字指定它似乎多余,而且由于您并未真正创建Task对象,因此很混乱.

Specifying it seems redundant with the async keyword plus it is confusion since you do not really create the Task object.

据我了解,编译器确实会发出创建Task对象所需的代码(无论是在等待调用中还是用新Task包装返回的内容.)

As I understand the compiler does emit the necessary code for Task object creation (Whether on a await call or wrapping the return with a new Task.).

我真的不喜欢声明类型和返回类型之间的不一致.

I don't really like the inconsistency between the declare type and the return Type.

推荐答案

我有已考虑,但他们决定不这样做.

I have a blog post that describes the reasoning in detail. Inferring the return type was considered but they decided not to.

对于显式返回类型,async关键字更多地是实现细节.具有显式返回类型的原因有两个:

With the explicit return type, the async keyword is more of an implementation detail. There are two reasons to have the explicit return type:

  • 方法签名是一致的(声明时与使用IntelliSense或反射观察时是相同的).
  • async voidasync Task之间存在差异.对于推断的返回类型,没有明确的方法来定义async void方法.
  • The method signature is consistent (it's the same at the point of declaration as when observed using IntelliSense or reflection).
  • There is a difference between async void and async Task. With an inferred return type, there's no clear way to define an async void method.

这篇关于在异步返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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