如果我要返回Task而不等待任何东西,我应该使用async吗 [英] Should I use async if I'm returning a Task and not awaiting anything

查看:270
本文介绍了如果我要返回Task而不等待任何东西,我应该使用async吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一种异步方法中,其中的代码没有await执行任何操作,是否有人为什么将其标记为异步,等待任务然后返回?

In an async method where the code is not awaiting anything, is there a reason why someone would mark it async, await the task, and then return?

除了可能不需要它外,这样做的负面影响是什么?

Besides the potential un-necessity of it, what are the negative ramifications of doing so?

对于此示例,请假定QueryAsync<int>返回Task<int>.

private static async Task<int> InsertRecord_AsyncKeyword(SqlConnection openConnection)
{
    int autoIncrementedReferralId =
        await openConnection.QueryAsync<int>(@"
            INSERT INTO...
            SELECT CAST(SCOPE_IDENTITY() AS int)"
    );

    return autoIncrementedReferralId;
}

private static Task<int> InsertRecord_NoAsyncKeyword(SqlConnection openConnection)
{
    Task<int> task =
        openConnection.QueryAsync<int>(@"
            INSERT INTO...
            SELECT CAST(SCOPE_IDENTITY() AS int)"
    );

    return task;
}

// Top level method
using (SqlConnection connection = await DbConnectionFactory.GetOpenConsumerAppSqlConnectionAsync())
{
    int result1 = await InsertRecord_NoAsyncKeyword(connection);
    int result2 = await InsertRecord_AsyncKeyword(connection);
}

推荐答案

不,您不应该在没有await的情况下仅将async添加到方法中-甚至会有编译器警告.

No, you should not just add async to method without await - there is even compiler warning for it.

您也不应该在这种方法内不必要地添加await,因为它会使编译器为该方法生成明显更复杂的代码,并带来一些相关的性能隐患.

You also should not needlessly add await inside such method as it will make compiler to generate significantly more complicated code for the method with some related performance implications.

从时序的角度来看,两种模式之间没有可观察到的差异-任务仍将异步运行,并且您仍然可以立即或在调用方中稍后等待.

There is no observable difference between two patterns from timing point of view - task will still run asynchronously and you still be able to await immediately or at later point in caller.

我可以想到一个区别-如果您直接返回任务,则调用方可以使用ConfigureAwait(false),它将在其他线程上完成.当您在自己的内部执行await任务时,该方法将控制执行await之后的代码的位置.

There is one difference I can think of - if you return task directly caller may use ConfigureAwait(false) and it will finish on other thread. When you await that task inside you method that method controls where code after await is executed.

请注意,最后使用单个await的方法的成本不会比不使用-c的方法的成本显着降低-因此,如果您更喜欢在所有异步方法上一致使用async的编码样式,则除少数时间紧迫的代码外,它可能还不错

Note that cost of method with single await at the end is not significantly worse than one without - so if you prefer for coding style consistent usage of async on all asynchronous methods it is likely fine except rare time critical pieces.

这篇关于如果我要返回Task而不等待任何东西,我应该使用async吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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