异步/等待中的return语句在哪里 [英] Where is the return statement in async/await

查看:56
本文介绍了异步/等待中的return语句在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能使自己陷入了一个不成熟的混乱之中.请参考下面的代码(控制台应用程序)

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.

所以问题是

  1. 什么是从Blah方法返回Task而不在我那里没有return语句的,为什么同一件事没有从ReturnsVoid方法返回任何东西.
  2. 如何控制从Blah方法返回的内容?如果我一个接一个地有两个等待语句怎么办?
  1. What is returning a Task from the Blah method without my having a return statement there and why is that same thing not returning anything from ReturnsVoid method.
  2. 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 awaits 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屋!

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