Kaladin
Kaladin

Reputation: 803

Alternative to Task.Run

I have an ASP.NET MVC 4 program and I wrote the following code where I wanted to make the Results() method async:

public async Task<ActionResult> Results()
{
  var result1 = SomeMethodAsync(1);
  var result2 = SomeMethodAsync(2);
  var result3 = SomeMethodAsync(3);

  await Task.WhenAll(result1, result2, result3);

  ViewBag.Result1 = result1;
  ViewBag.Result2 = result2;
  ViewBag.Result3 = result3;

  return View()

}


public async Task<int> SomeMethodAsync(int i)
{
  //do some logic

  //make db call
  return await Task.Run( () => DbCall(i));
 }


 public int DbCall(i)
 {
   //make db call

   return valueFromDb;
 }

Since I am not using Entityframework 6 I cannot make the DbCall() async. I was reading that its not a good idea to use Task.Run in ASP.NET projects since Task.Run will borrow a thread from the ASP.Net thread pool and therefore can cause queuing issues with large number of requests (as there will be lower number of available threads for processing incoming requests).

1) How can I make my method async without using Task.Run?

2) Is it better to make the method synchronous than using Task.Run ?

Upvotes: 2

Views: 2761

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456457

2) Is it better to make the method synchronous than using Task.Run ?

Yes.

In this case, since you don't have naturally-asynchronous APIs available from EF6, the next best solution is to just be synchronous.

Note that even if you did have asynchronous APIs, a single DbContext can only handle one operation at a time anyway. You'd have to create multiple contexts in order to run multiple simultaneous queries, and that can get complex.

Upvotes: 3

Related Questions