The following code compiles correctly:
public ContextStatus Commit(string userName)
{
var status = new ContextStatus();
var task = Task.Run(async () => { status = await CommitAsync(userName, new CancellationToken()); });
task.Wait();
return status;
}
public async Task<ContextStatus> CommitAsync(string userName, CancellationToken ct)
{
var status = new ContextStatus();
try
{
if (this.Database.Connection.State == ConnectionState.Closed)
{
await this.Database.Connection.OpenAsync(ct).ConfigureAwait(false);
}
using (var command = this.Database.Connection.CreateCommand())
{
SqlParameter param = new SqlParameter()
{
ParameterName = "@user",
SqlDbType = SqlDbType.VarChar,
Size = 127,
Value = userName
};
command.CommandText = "setcontextinfo";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(param);
await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
}
await base.SaveChangesAsync(ct).ConfigureAwait(false);
}
catch (DbEntityValidationException dbEx)
{
status.SetErrors(dbEx.EntityValidationErrors);
}
catch (DbUpdateException duEx)
{
status.SetErrors(duEx);
if (!status.DatabaseErrors.Any())
throw;
}
return status;
}
Questions:
- Will this CommitAsync method execute synchronously in the Commit method?
- Is it best practive to pass new CancellationToken() in the Commit method?
- Will the base.SaveChangesAsync() call in CommitAsync() close the connection if it was opened beforehand?