Using the async / await method in an MVC controller action can scale the web application because Asp.Net thread pool request pool waiting is freed up so that it can handle other requests in the IIS queue for this workflow. This means that if we limit the length of the workflow queue to 10 and send 50 - 100 requests for asynchronous action, IIS should not return an HTTP 503 error, since there will always be free flow from the Asp.Net thread pool for the server incoming requests.
I have a WebApi that performs the calculation as follows:
public class ValuesController : ApiController
{
public int GetSum(int x, int y, int timeDelay = 1)
{
Thread.Sleep(timeDelay*1000);
int result = x + y;
return result;
}
}
This action method simply delays the specified number of seconds before returning the result of the sum to the calling code. Very simple web api just to simulate a long code.
MVC, :
public class ThreadStarvationController : Controller
{
public async Task<ActionResult> CallGetSumWithDelayAsync(int num1 = 5, int num2 = 8, int timeDelay = 60)
{
int callingThreadId = Thread.CurrentThread.ManagedThreadId;
ThreadStarvationModel model = new ThreadStarvationModel();
string url = "http://localhost:8111/api/values/GetSum?x=" + num1 + "&y=" + num2 + "&timeDelay=" + timeDelay;
using (HttpClient client = new HttpClient())
{
model.ResponseFromWebService = await client.GetStringAsync(url);
}
int returningThreadId = Thread.CurrentThread.ManagedThreadId;
model.CallingThreadId = callingThreadId;
model.ReturningThreadId = returningThreadId;
return this.View(model);
}
}
WebApi MVC IIS. - MVC 10 .
MVC 15 20 , IIS HTTP 503 , , IIS .
, async MVC. 30 .
List<Task> taskList = new List<Task>();
for (int x = 0; x < 30; x++)
{
string url = "http://localhost:8333/ThreadStarvation/CallGetSumWithDelayAsync?num1=" + x + "&num2=" + x + "&timeDelay=1";
Task stringDataTask = new Task(() =>
{
using (HttpClient webClient = new HttpClient())
{
string data = webClient.GetStringAsync(url).Result;
Console.WriteLine("{0}", data);
}
});
taskList.Add(stringDataTask);
}
DateTime startTime = DateTime.Now;
Parallel.ForEach(taskList, item => item.Start());
Console.WriteLine("================== START {0} ===========================", startTime);
Task.WaitAll(taskList.ToArray());
DateTime endTime = DateTime.Now;
Console.WriteLine("================= THE END {0} ============================", endTime);
, 20 HTTP 503.
MVC, . , / .
, , , async/await -.