views:

48

answers:

2

Not been able to find a definitive answer to this, when a client session is established to an ASP.NET MVC2 application I assume a particular thread from a thread pool handles that request. Does the same thread always handle all subsequent requests for that session? So in theory if somehow the session id were messed up and the wrong thread picked then any session level data would be missing? Thanks

A: 

No. Each request can be handled by a different thread. This means that various resources on a page can be handled by different threads. Or they might be handled on the same one. It is up to the worker process and iis to sort out whether it is worthwhile creating a new thread or better to wait till one becomes available.

The page will be rendered by one thread and then the images, style sheets and javascripts can be handled on the same or other threads. This is fundamental to the stateless nature os ASP.NET and web programming in general. What it allows you to do though is to load balance all of your requests across different servers or even different domains.

This brings us to your question about Session State. You shouldn't be losing session ids between requests. If you are, something serious is wrong. Or you could be in a web farm/cluster situation where one request is going to one server and the next is routed to another through some kind of load balancing.

In a load balanced scenario you have to have some means of persisting session state. The two most common approaches are saving to a Database and to a distributed cache. The later is my prefered approach because session data is by its very nature a temporary thing and doesn't belong in a persistent db.

Daniel Dyson
+1  A: 

In short, no, not under IIS (I can't vouch for the "Cassini" web development server in Visual Studio, but I doubt there too)

You can demonstrate the thread changing by adding the following to a view:

<%= System.Threading.Thread.CurrentThread.ManagedThreadId %>

Now repeatedly hit the page from your browser (or maybe hit it from 2 or 3 browsers) and you will see it change from time to time.

Having said that - in a simple scenario such as this, you may often see the same thread servicing the request as it is not worth ASP.NET creating more threads than it needs, but once you start loading the server, you will see multiple threads.

Rob Levine