Craig Warren
Craig Warren

Reputation: 1665

How is ASP.NET multithreaded?

I've been told that ASP.NET is multithreaded by default in IIS. How is this threading achieved?

Does the server farm send different requests to different cores?

Does a single request make use of multiple cores?

More importantly, are there any advantages to adding threads to ASP.NET code if the threading is done higher up in IIS?

Upvotes: 27

Views: 21993

Answers (4)

TheTXI
TheTXI

Reputation: 37875

IIS makes use of the multiple cores automatically (although you can turn it off if you so choose).

The advantage to adding threads to ASP.NET code is so that you can control your own application's inner workings and not be forced to rely on IIS to make all the decisions for you.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1499660

Not only does the server farm different requests to different threads, but a single request can change thread during the course of life cycle. This is called thread agility. I'm looking for a good article explaining it...

EDIT: No definitive articles yet, but one blog post explaining some of the difficulties.

EDIT: More links from comments:

Upvotes: 25

Andrew Harry
Andrew Harry

Reputation: 13909

ASP.net uses the .Net threadpool (which is configurable) Each request is received by one of the threads in the threadpool, until each thread is already occupied. Then requests queue at the IIS Stack, until this also spills over. From there new requests are meet with the very ugly 'Server is unavailable' message.

This is the usual 'multi-threading' story for a ASP.net website.

There are many ways to ensure scalability. The most obvious being performance testing and removing bottlenecks from your code.

ASP.net can really take advantage of multiple cores by utilizing the I/O threads for any I/O request. It makes for ugly code but fast has never been pretty.

Here is the definitive MSDN MAG post on how to do this

UPDATE

Well I probably attempt to answer your full question:

"More importantly is there any advantage to adding threads to ASP.Net code if the threading is done higher up in IIS?"

The short answer is: It depends! If you are waiting on a long running process, then you would be better advised to implement a nicer experience for the requesting client (i.e. Out of band AJAX calls)

if you have multiple independent tasks that need to be completed for the requesting client: then you might be better off spawning a new process to run the tasks in parallel.

If your site gets lots of traffic, then you really need to consider implementing Asynchronous patterns to better utilise your CPU

Upvotes: 9

sharptooth
sharptooth

Reputation: 170479

A separate thread is usually spawned for each new request, then the operating system does processor scheduling. Unless you need to process just a few requests at a time you don't need extra threading.

Upvotes: 3

Related Questions