Am I using the Asynchronous Task correctly?

Asked

Viewed 18 times

1

Hello,

I am doing a project in ASP.NET MVC and wanted to use an asynchronous task. In my stock I have:

public async Task GerarItens(int codigo)
{ 
    using (var dbTran = dbContext.Database.BeginTransaction())
    {
         try
         {
              >> VARIOS SELECTs, UPDATEs, INSERTs <<
              dbTran.Commit;
              await Task.FromResult<object>(null);
          }
          catch (Exception)
          {
              dbTran.Rollback();
              throw;
          }
     }
}

On my controller I have:

private async Task GeradorItens(int codigo)
{
    RepoExemplo repo = new RepoExemplo();
    await repo.GerarItens(codigo);
}

public async Task<ActionResult> Listagem(int codigo)
{
    try
    {
        RepoExemplo repo = new RepoExemplo();

        await GeradorItens(codigo);

        return View(repo.Listar(codigo));
     }
     catch (Exception ex)
     {
         return View("Error", ex.Message);
     }
 }

Doubts:

  1. I can use the dbTran within a async task?
  2. When I use the await? In my GerarItens of Repositorio, I would use in all my Selects, Inserts, Updates?

    2a. If case, example, I need to make a select after a insert, only in that insert i put a await, I’ll get the right result on my select?

    2b. What I understood on the subject (speaking very layily), the await ago the task in the background, so in my example if the insert take long to be done, my select will not perform with the information that this insert would generate, correct?

  3. What return options do I have for a method TASK? I used the await Task.FromResult<object>(null); because I didn’t know what to put...

  4. public async Task<ActionResult> Listagem, it is correct to use this for what I am wanting to do?
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.