Reputation: 592
I am trying to test MVC4 async controller actions which I have read most about from here: http://www.asp.net/mvc/tutorials/mvc-4/using-asynchronous-methods-in-aspnet-mvc-4
Below is my controller:
public class HomeController : AsyncController
{
//
// GET: /Home/
public async Task<ActionResult> Index()
{
WriteOnFile("Here dude. Time: " + DateTime.Now.ToString("HH:mm:ss:fff"));
await Task.Delay(10000);
return View();
}
private void WriteOnFile(string text)
{
using (Mutex mutex = new Mutex(false, "TempFile"))
{
mutex.WaitOne();
using (var writer = new StreamWriter(@"D:\Temp\temp.txt", true))
{
writer.WriteLine(text);
}
mutex.ReleaseMutex();
}
}
}
I am testing this by opening 5 browser tabs pointing to ~/home/index and refreshing them all at once.
Below is the output I am getting:
The time-stamps are 10 seconds apart. Which means each request is being handled after the previous one completes. Which is what synchronous controller actions do, but I hoped that asynchronous controller actions would handle requests while waiting. Why is async not working in the above example? Anything that I'm doing wrong?
I am using IIS 8.5 in Windows 8.1 with .net 4.5.
Thanks in advance.
Upvotes: 1
Views: 2674
Reputation: 13373
ASP.NET MVC depends upon session state by default. ASP.NET will block concurrent requests from the same source if they depend upon session state. This is why you have seeing your concurrent requets being executed once at a time. See this question for further explanation.
Furthermore, AsyncController is obsolete. Use the normal controller instead, any method that you wrap in async/Task/Task is automatically async just as they would be in normal code.
You have two choices: Disable dependency upon session or use Web API which by default does not depend upon session and thus will run concurrently.
Upvotes: 5