Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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:

  1. Will this CommitAsync method execute synchronously in the Commit method?
  2. Is it best practive to pass new CancellationToken() in the Commit method?
  3. Will the base.SaveChangesAsync() call in CommitAsync() close the connection if it was opened beforehand?
share|improve this question
    
Normally you would have a regular method and an Async method that wrap/call your regular method but you seem to be doing the oposite. If I were to use your code a call Commit, it turn out to be Async. While calling CommitAsync turns out to be non async? –  Tien Dinh Dec 27 '14 at 18:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.