在异步方法结束时,我应该返回还是等待? [英] At the end of an async method, should I return or await?

查看:33
本文介绍了在异步方法结束时,我应该返回还是等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在返回任务的异步方法结束时,如果我调用另一个异步方法,我可以await 它或return 它的任务.各自的后果是什么?

At the end of a Task-returning async method, if I call another async method, I could either await it or return its task. Which are the consequences of each?

    Task FooAsync()
    {
        return BazAsync();  // Option A
    }

    async Task BarAsync()
    {
        await BazAsync(); // Option B
    }

推荐答案

如果方法本身被声明为 async,你就不能返回任务 - 所以这将不起作用,例如:

You can't return the task if the method itself is declared to be async - so this won't work, for example:

async Task BarAsync()
{
    return BazAsync(); // Invalid!
}

那将需要 Task 的返回类型.

That would require a return type of Task<Task>.

如果您的方法只是做了少量工作,然后只是调用一个异步方法,那么您的第一个选项就可以了,这意味着所涉及的任务少了.您应该知道,同步 方法中抛出的任何异常都将同步传递 - 实际上,这就是我更喜欢处理参数验证的方式.

If your method is just doing a small amount of work and then calling just one async method, then your first option is fine, and means there's one fewer task involved. You should be aware that any exceptions thrown within your synchronous method will be delivered synchronously though - indeed, this is how I prefer to handle argument validation.

这也是实现重载的常见模式,例如通过取消令牌.

It's also a common pattern for implementing overloading e.g. by cancellation token.

请注意,如果您需要更改以等待其他内容,则需要将其设为异步方法.例如:

Just be aware that if you need to change to await something else, you'll need to make it an async method instead. For example:

// Version 1:
Task BarAsync()
{
    // No need to gronkle yet...
    return BazAsync();
}

// Oops, for version 2 I need to do some more work...
async Task BarAsync()
{
    int gronkle = await GronkleAsync();
    // Do something with gronkle

    // Now we have to await BazAsync as we're now in an async method
    await BazAsync();
}

这篇关于在异步方法结束时,我应该返回还是等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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