I have the following method which commits changes to a db (using Entity Framework):
public async Task<int> CommitAsync(Info info)
{
if (this.Database.Connection.State == ConnectionState.Closed)
await this.Database.Connection.OpenAsync();
await SetInfo(info);
return await base.SaveChangesAsync();
}
Is the above method safe to use as is, or should I:
async-await
, orContinueWith
It's absolutely fine to have multiple await
expressions in the same async method - it would be relatively useless feature otherwise.
Basically, the method will execute synchronously until it reaches the first await
where the awaitable involved hasn't already completed. It will then return to the caller, having set up a continuation for the awaitable to execute the rest of the async method. If execution later reaches another await
expression where the awaitable hasn't already completed, a continuation is set up on that awaitable, etc.
Each time the method "resumes" from an await, it carries on where it left off, with the same local variables etc. This is achieved by the compiler building a state machine on your behalf.
See more on this question at Stackoverflow