async方法与普通方法不同。从
async方法返回的所有内容都包装在
Task。
如果不返回任何值(无效),则将其
Task换行;如果返回
int,则将其换行
Task<int>,依此类推。
如果您的异步方法需要返回
int你标记方法的返回类型
Task<int>,你会返回纯
int不是
Task<int>。编译器将转换
int到
Task<int>你。
private async Task<int> MethodName(){ await SomethingAsync(); return 42;//Note we return int not Task<int> and that compiles}同样,返回时,
Task<object>方法的返回类型应为
Task<Task<object>>
public async Task<Task<object>> MethodName(){ return Task.FromResult<object>(null);//This will compile}由于您的方法正在返回
Task,因此不应返回任何值。否则它将无法编译。
public async Task MethodName(){ return;//This should work but return is redundant and also method is useless.}请记住,没有
await声明的异步方法不是
async。



