writing async Repository methods inside my asp.net mvc5 web application

asp.net-mvc asp.net-mvc-5 async-await asynchronous entity-framework-6

Question

I am working on an asp.net mvc5 web application + Entity Framework 6. and I want to have a repository model class inside my application. currently I am following this approach to have async action methods and async repository model class.

for example I have the following repository save method:

public class Repository
{
    private Entities t = newEntities();

    public async Task Save()
    {
        await t.SaveChangesAsync();
    }

which I am calling from my action methods as follow:

Repository repository = new Repository();
 public async Task<ActionResult> GetResourceByName(string resourcename)
      {
         await  repository.Save();
      }

so is this a correct approach? as I am doing the following:

  1. I define the repository method as a Task & also the Action method as Task. so should I have both of them as Task(s).?

  2. I am using await twice on the action method (when calling the repo method) and on the repository? so are these await redundant?

//please note that this is only a simple example of a repository method which is just used to save model,, but I am asking about the approach itself as I will be using this approach in a more complex repository methods ..

1
1
6/29/2019 3:15:47 PM

Popular Answer

Contrary to both answers two awaits are not necessary. await and async are only necessary if you need the result from a Task before continuing. If you don't need that result then you don't need to mark your method async.

This means this method...

public async Task Save()
{
    await t.SaveChangesAsync();
}

Can be simplified into

public Task Save()
{
    return t.SaveChangesAsync();
}

Even though these are functionally the same, I like the second version because it shows recognition that Task is the asynchronous work and async/await are only signals to the compiler to wait for that work to complete.

2
9/7/2015 5:09:12 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow