异步等待返回任务 [英] async await return Task
问题描述
有人能解释一下这是否意味着进入一个同步的方法是什么?如果我试图改变方法异步
然后VS抱怨。
Can somebody explain what does this means into a synchronous method? If I try to change the method to async
then VS complain about it.
本作品:
public Task MethodName()
{
return Task.FromResult<object>(null);
}
这不工作:
public async Task MethodName()
{
return Task.FromResult<object>(null);
}
所以基本上我想知道究竟是什么,这意味着: Task.FromResult&LT;对象&gt;(NULL);
推荐答案
异步
方法比普通方法不同。无论你从返回异步
方法被包裹在一个工作
。
async
methods are different than normal methods. Whatever you return from async
methods are wrapped in a Task
.
如果你没有返回值(无效),它将被包裹在工作
,如果返回 INT
它会被包裹在任务&LT; INT方式&gt;
等
If you return no value(void) it will be wrapped in Task
, If you return int
it will be wrapped in Task<int>
and so on.
如果您的异步方法需要返回 INT
你标记方法的返回类型为任务&LT; INT&GT;
,你会返回纯 INT
不是任务&LT; INT&GT;
。编译器将转换 INT
到任务&LT; INT方式&gt;
你
If your async method needs to return int
you'd mark the return type of the method as Task<int>
and you'll return plain int
not the Task<int>
. Compiler will convert the int
to Task<int>
for you.
private async Task<int> MethodName()
{
await SomethingAsync();
return 42;//Note we return int not Task<int> and that compiles
}
同一开头,当您返回任务&LT;对象&gt;
你的方法的返回类型应该是任务&LT;任务&LT;对象&gt;&GT;
Sameway, When you return Task<object>
your method's return type should be Task<Task<object>>
public async Task<Task<object>> MethodName()
{
return Task.FromResult<object>(null);//This will compile
}
由于您的方法返回工作
,它应该不会返回任何值。否则将无法编译。
Since your method is returning Task
, it shouldn't return any value. Otherwise it won't compile.
public async Task MethodName()
{
return;//This should work but return is redundant and also method is useless.
}
记
记住,没有一个等待
语句异步方法不是异步
。
这篇关于异步等待返回任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!