The easiest way to make the controller asynchronous

I have inherited a large web application that uses MVC5 and C #. Some of our controllers make several slow database calls, and I want to make them asynchronous to allow worker threads to serve other requests, waiting for the database calls to complete. I want to do this with the least amount of refactoring. Say I have the following controller

public string JsonData()
{
   var a = this.servicelayer.getA();
   var b = this.servicelayer.getB();
   return SerializeObject(new {a, b});
}

I made two expensive calls a, b asynchronous, leaving the service level unchanged and rewriting the controller as

public async Task<string> JsonData()
{
   var task1 = Task<something>.Run(() => this.servicelayer.getA());
   var task2 = Task<somethingelse>.Run(() => this.servicelayer.getB());
   await Task.WhenAll(task1, task2);
   var a = await task1;
   var b = await task2;
   return SerializeObject(new {a, b});
}

- , , Visual Studio, Task.Run() asp.net , , . - - ? , , async . , , , async? , , , , . 2 ? - 2 , ?

+4
2

, , - A B, . .

Task.Run, , 2 , ( )

, (- parallelism), .


, , , . servicelayer.getAAsync() servicelayer.getBAsync(), IO:

public async Task<string> JsonData()
{
    return SerializeObject(new {await servicelayer.getAAsync(), await servicelayer.getBAsync()});
}

, - , .

, Task.Run: Task.Run Etiquette : Task.Run

+2

, async , I/O. I.e., . -.

, Task.Run - , " ". , ASP.NET.

" " - . , EF6 . async .

+6

Source: https://habr.com/ru/post/1543634/


All Articles