I am trying to demonstrate to a junior the importance of asynchronous programming, using async
and await
. For the purpose I have created an ASP.NET Web API project with one controller and two GET actions. One GET action is synchronous and the other is asynchronous.
I want to demonstrate that, in case of synchronous blocking i/o call, all of the available ASP.NET worker threads are waiting and doing nothing useful and in the meantime when some more requests arrive they will time out as all the available threads are waiting for i/o threads to complete.
The problem is that that my below code snippet partly conveys the point. it works as intended in case of asynchronous calls but not for synchronous calls. If I uncomment the commented out code lines, it doesn't happen and ASP.NET runtime can cope with many more threads. The code snippet is below:
public class TestController : ApiController
{
// -> Uncommenting the below method proves my point of scalability <-
//public async Task<string> Get()
//{
// CodeHolder obj = new CodeHolder();
// return await obj.AsyncData();
//}
// -> Uncommenting the below method doesn't enforce time outs, rather waits <-
public string Get()
{
CodeHolder obj = new CodeHolder();
return obj.SyncData();
}
}
class CodeHolder
{
public string SyncData()
{
Task.Delay(10000).Wait();
return $"I am returned from Sync after waiting for 10 second at {DateTime.Now.ToString("HH:mm:ss:fffffff")}";
}
public async Task<string> AsyncData()
{
await System.Threading.Tasks.Task.Delay(10000);
return $"I am returned from Async after semi-waiting for 10 second at {DateTime.Now.ToString("HH:mm:ss:fffffff")}";
}
}
Although the point I was trying to propose, gets conveyed as the synchronous calls take ages to complete but I am wondering why the requests are being kept in queue instead of time outs. I am using JMeter for sending 250 concurrent HTTP requests to my Web API service but they never time out rather they keep waiting and complete, although a very large delay (~250 seconds).
By the way, in async version, all of the responses are returned in around 10 seconds.