Reputation: 18600
In an async method where the code is not await
ing 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);
}
Upvotes: 13
Views: 3520
Reputation: 100547
No, you should not just add async
to method without await
- there is even compiler warning for it.
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.
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.
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.
Upvotes: 7