Carlos Miguel Colanta
Carlos Miguel Colanta

Reputation: 2823

Asynchrony on ASP MVC

I would want to increase the performance of my web application for future scalability issues,

One scenario that i think of is that, if i need a list that needs to be filtered from the database.

Here is the rough draft that i made:

public IEnumerable<test> getL(IEnumerable<test> filter)
{
        //do some filtering from the list then return it
        return filter;
}



public async Task<ActionResult> Index()
{
      context con = new context();       
      //do more stuff of stuff
      IEnumerable<test> get = await Task.Run(() => { return getL(con.dep.ToList()); });   
      return View(get);
}

I am kinda new with C#'s asynchrony so i am kinda wondering if i am doing this correct. Did i start the asynchronous call properly?

Upvotes: 0

Views: 39

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457302

On ASP.NET, you should avoid Task.Run. This is because Task.Run will free up the current thread by using another thread. So you incur the penalty of an additional context switch for no reason. This code will decrease scalability and performance, not increase it.

Instead, use await for I/O-based tasks. For example, getting the data from the database:

public async Task<ActionResult> Index()
{
  context con = new context();       
  var list = await con.dep.ToListAsync();
  IEnumerable<test> get = getL(list);
  return View(get);
}

Upvotes: 1

Related Questions