异步/等待中的return语句在哪里 [英] Where is the return statement in async/await
问题描述
我可能使自己陷入了一个不成熟的混乱之中.请参考下面的代码(控制台应用程序)
I have probably worked myself into a rather immature confusion. Please refer the code below (console app)
namespace Tasks101
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
var x = p.Blah();
}
private async Task Blah()
{
await Task.Delay(TimeSpan.FromSeconds(3)).ConfigureAwait(false);
}
private async void ReturnsVoid()
{
await Task.Delay(TimeSpan.FromSeconds(3)).ConfigureAwait(false);
}
private void Nothing()
{
}
}
}
我的问题是,在Blah()
方法中,执行该方法时我还没有任何显式的return语句
My question is that in Blah()
method I don't have any explicit return statement yet when this executes
var x = p.Blah();
x
的类型是Task
.再次,我在ReturnsVoid
方法中没有return语句,但是也可以编译.
the type of x
is Task
. Again I have no return statement in ReturnsVoid
method but that compiles too.
所以问题是
- 什么是从
Blah
方法返回Task
而不在我那里没有return
语句的,为什么同一件事没有从ReturnsVoid
方法返回任何东西. - 如何控制从
Blah
方法返回的内容?如果我一个接一个地有两个等待语句怎么办?
- What is returning a
Task
from theBlah
method without my having areturn
statement there and why is that same thing not returning anything fromReturnsVoid
method. - How do I control what gets returned from the
Blah
method? What if I had two await statements there one after the other?
推荐答案
async
关键字转换方法并构造返回的Task
实例. async void
方法没有返回任何内容,因为它返回了void
.缺少Task
是您应避免使用async void
的原因之一. async void
不是 natural 异步方法签名;它仅受支持,因此事件处理程序可能是async
.
The async
keyword transforms the method and constructs the returned Task
instance. There is nothing returned from the async void
method because it returns void
; this lack of a Task
is one reason why you should avoid async void
. async void
is not a natural asynchronous method signature; it is only supported so that event handlers may be async
.
如果要返回值,则应让该方法返回Task<T>
,例如Task<int> BlahAsync()
,然后可以直接返回值,例如await
的数量与之无关.当该方法执行实际的返回值(例如return 13
)时,async
关键字将其解释为完成已构建的Task<int>
.
If you want to return a value, then you should have the method return a Task<T>
, e.g., Task<int> BlahAsync()
, and then you can just return the value directly, e.g., return 13;
The number of await
s in the method has nothing to do with it. When the method executes the actual return (e.g., return 13
), the async
keyword interprets that as completing the Task<int>
that was already constructed.
我的博客上有一个 async
简介可能对您有所帮助.
I have an async
intro on my blog that you may find helpful.
这篇关于异步/等待中的return语句在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!