Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use async if I'm returning a Task and not awaiting anything

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?

For this example, please assume that QueryAsync<int> returns 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);
}
like image 984
contactmatt Avatar asked Jan 13 '17 01:01

contactmatt


People also ask

Should I use async without await?

In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously. Code after each await expression can be thought of as existing in a .then callback.

What happens if you call an async method without await?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

When should you use async await?

Async/Await makes it easier to write promises. The keyword 'async' before a function makes the function return a promise, always. And the keyword await is used inside async functions, which makes the program wait until the Promise resolves.


1 Answers

Read this blog post from Stephen Cleary:

Eliding Async and Await

like image 118
Paulo Morgado Avatar answered Oct 14 '22 06:10

Paulo Morgado