ASP.NET Multithreading Web Requests

Derek picture Derek · May 28, 2014 · Viewed 22.8k times · Source

I'm building a page in my ASP.NET solution that retrieves most of its data from a 3rd Party API Service.

The page itself will need to make approximately 5 individual different calls to the API to populate all of its controls, as each Web Request to the API brings back different sets of Data.

I would like to deal with each separate Web request i make on a new thread, simultaneously so that load time is reduced.

Each request I'm making looks like this :-

WebRequest request = WebRequest.Create(requestUrl);

string response = new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();

return new JsonSerializer().Deserialize<OccupationSearch>(new JsonTextReader(new StringReader(response)));

Firstly, should i be attempting this? i.e, is it safe? and will it enhance performance by multi-threading this out.

Secondly, what is the best way to go about doing this? There's many different ways to multi-thread systems, but which will suit this task best?

Answer

Mat&#237;as Fidemraizer picture Matías Fidemraizer · May 28, 2014

Multi-threading is the right choice, but I would call it doing stuff asynchronously.

Anyway, you should know that multi-threading works different in IIS.

IIS worker process will finish a request once all child threads end, and this is a big problem, because you don't want to hold a worker process for a long time but re-use it for other requests. Actually it's a thread pool.

This is why ASP.NET offers its own approach to implement asynchronity and if you use the right approach, IIS will be able to process more requests at once because asynchronous work will be executed outside IIS process model.

I would suggest you to read more about ASP.NET async:

Conclusion: use asynchronous work and this will make a more efficient use of server resources, but first learn more about how to do it in the right way!