Understanding ASP.Net instances and threading - asp.net

Looking at a very simple web project, hosted in IIS, with one simple aspx page, executing some code (get some data from a db and populate some controls), which of the following is true:
each page request shares the same instance of the codebehind class.
or each page request runs in its own instance of the codebehind class.
Does one thread/instance run against each aspx page. Or does one thread/instance cover multiple pages?
Im trying to understand, in a simple web project, that receives 100 page requests, will they run consecutively one after the other, or multiple instances/threads for each request?

Each request gets a new instance of the code-behind class.
One instance of the code-behind class serves one request.
Two requests at different points in time may run on the same thread from the thread pool.
Two requests that runs in parallell gets one thread each (I think; not 100% sure on if there are some corner cases that I am not aware of regarding the threading).
So, a web server can handle several requests in parallell, but there is of course a limit on how many requests that can be served at the same time.

There is one instance of the code behind class for each request.
Well, actually it's an instance of the aspx page class, that inherits from the code behind class. (That's why you are using the protected keyword for event handlers in code behind, so that the inheriting class can access them.)
There is also the case where you do a Server.Transfer or Server.Execute, then the request is transfered to another page instance.
There are several threads running in the IIS handling requests, and usually one request is handled in one thread, but a request can be moved from one thread to another in some situations.
If 100 requests arrive at the server, it will start processing a few of them in separate threads, and put the rest of them in a queue. Noteworthy is that the server will only process one page at a time from each user, so unless you use sessionless pages (to make them anonymous) it will not process two pages for the same user in parallel threads, which makes the whole threading part a lot easier.

Maybe take a look at asynchronous ASP.NET?
http://msdn.microsoft.com/en-us/magazine/cc163725.aspx
Normally a new thread is assigned to a new request.
"A normal, or synchronous, page holds onto the thread for the duration of the request, preventing the thread from being used to process other requests."

Related

HttpApplication events changing threads

For logging purposes of an ASP.NET web application, I keep some state information in a static class. These fields are marked [ThreadStatic] so every thread has its own copy of the field. The logging methods are called from the HttpApplication event methods:
Application_BeginRequest (request start, initialise state)
Application_AcquireRequestState (session and user are known)
Application_EndRequest (request end, clean up)
I can now observe that, under certain circumstances, a page request is processed in different threads. The BeginRequest event runs on thread 18 while the following events run on thread 4. Of course my thread-static data is then not available and an error occurs.
Most of the time this works just fine and every request is processed in a single thread only. But when I request a page that loads ~5 seconds and after 1-2 seconds click on another link, both requests run in parallel. The first is completed on thread 24 (where it was also started) after 5 seconds, while the other starts on thread 18, but after the first request has completed, the second continues to run on thread 4.
Trying it with 3 overlapping long requests, it's a pure chaos. I can even watch two requests starting on the same thread while they later continue on different threads each. There doesn't seem to be any relationship between a request and a thread.
How can it be that a request is changing threads? It's losing all of its state if it decides to move on to another thread. And every description I can find says that it all happens in a single thread.
ASP.NET 4.0 on IIS 7, Windows Server 2008 R2, x64.
Alternative: If I cannot rely on requests being processed in only a single thread from the start to the end, then what would be the best location to store small amounts of per-request data (currently an integer and a class) that is very fast accessibly? And preferably also works without a reference to System.Web (my code is targeting the client profile as well). I know about HttpContext.Current.Items[key] but it's looked up somewhere deep in the remoting assembly and involves a dictionary which seems a lot slower than a thread-static field.
ASP.NET is thread agile and a request can be processed on more than one thread (but not more than one at time). Because of this you really can't use ThreadStatics in ASP.NET. However, you can safely use the HttpContext.Items dictionary to store things which need to be scoped to a single request.
To allow your code to work outside the context of an ASP.NET application, you could create a wrapper that swaps HttpContext / CallContext, depending on which environment the code is in. Here is an example of such a wrapper.

Does my ASP.Net MVC 3 application handle all incoming request one AFTER another

a colleague of my said that a MVC 3 app handles all incoming requests one at a time.
So when i make two AJAX calls to my application from a webpage, asp.net MVC / IIS handles the first request first, then returns the result and then processes the second request.
He has this line of documentation from MSDN of evidence (http://msdn.microsoft.com/en-us/library/ee728598(v=vs.98).aspx)
You can use asynchronous action methods for long-running, non-CPU
bound requests. This avoids blocking the Web server from performing
work while the request is being processed
Where it says that 'asynchronous action methods' don't block, so 'normal' controller actions do.
He also said that he saw that in effect on his page ( in the browser debug tools, lokking at the request sent), that first ajax request one was processed, and then, even that it was fired at the same time as the first by the browser, the second.
I find it hard to believe that IIS can only serve one request at a time per application?
If you are on the same session, then AJAX queries will be serialized (one at a time).
You can change your controller to be sessionless. See What are some scenario's of having a Session-less Controller in ASP.NET MVC3?.

Asp.net single threaded page requests

how to handle multiple http requests from a single client such that it is handled by single Asp.net thread. When PageAsyncTask or TPL is not an option as it does create a new thread. Code snipet will be of great help.
Each separate HTTP request will be executed on a potentially separate thread.
You have no control over which thread execution of your ASP.Net page is scheduled on.
I do not believe this can be accomplished.
Think about why you are trying to do this. Do you need to share some information between the various HTTP requests? If so, consider using a session or a cookie to manage that information.

ASP.NET concurrency

I have an ASP.NET application that starts a long running operation during the Event Handler phase in the ASP.NET Page life cycle. This occurs when the end user pushes a button a bunch of queries are made to a database, a bunch of maps are generated, and then a movie is made from jpeg images of the maps. This process can take over a minute to complete.
Here's a link to the application
http://maxim.ucsd.edu/mapmaker/cbeo.aspx
I've tried using a thread from the threadpool, creating and launching my own thread and using AsyncCallback framework. The problem is that the new thread is run under a different userid. I assume the main thread is run under ASPNET, the new thread is run under AD\MAXIM$ where MAXIM is the hostname. I know this because there is an error when it tries to connect to the database.
Why is the new thread under a different userid?
If I can figure out the userid issue, what I'd like to do is check if the movie making process has finished by examining a Session variable in a Page_Load method, then add a link to the page to access the movie.
Does anyone have any good examples of using concurrency in a ASP.NET application that uses or creates threads in an EventHandler callback?
Thanks,
Matt
Did you read this?: http://msdn.microsoft.com/en-us/magazine/cc163725.aspx
Quoting one relevant portion from that link (you should read the whole thing):
A final point to keep in mind as you build asynchronous pages is that you should not launch asynchronous operations that borrow from the same thread pool that ASP.NET uses.
Not addressing the specific problem you asked about, but this is likely to come up soon:
At what point is this video used?
If it's displayed in the page or downloaded by the user, what does the generated html that the browser uses to get the video look like? The browser has to call that video somewhere using a separate http request, and you might do better by creating a separate http handler (*.ashx file) to handle that request, and just writing the url for that handler in your page.
If it's for storage or view elsewhere you should consider just saving the information needed to create the video at this point and deferring the actual work until the video is finally requested.
The problem is that the new thread is run under a different userid. I assume the main thread is run under ASPNET, the new thread is run under AD\MAXIM$ where MAXIM is the hostname.
ASPNET is a local account, when the request travels over a network it will use the computer's credentials (AD\MAXIM$).
What may be happening, is that you're running under impersonation in the request - and without in the ThreadPool. If that's the case, you might be able to store the current WindowsIdentity for the request, and then impersonate that identity in the ThreadPool.
Or, just let the ThreadPool hit the DB with Sql Authentication (username and password).

best way to consume a webservice in an asp.net code behind

I'm trying to bind a datasource to a repeater, for instance, to a web service (.asmx from a different website) on page load. The webservice returns a DataSet from an sql call. What is the best way to go about doing this?
Because you're calling another website, you have to contend with two issues (especially if this web service is on somebody else's website or over the public internet). First, there might be a delay to retrieve the data from the other website. Second, the other website might timeout.
At a minimum you should consider an asychronous page request. As this MSDN article states:
If a synchronous request becomes I/O
bound—for example, if it calls out to
a remote Web service or queries a
remote database and waits for the call
to come back—then the thread assigned
to the request is stuck doing nothing
until the call returns. That impedes
scalability because the thread pool
has a finite number of threads
available. If all request-processing
threads are blocked waiting for I/O
operations to complete, additional
requests get queued up waiting for
threads to be free. At best,
throughput decreases because requests
wait longer to be processed. At worst,
the queue fills up and ASP.NET fails
subsequent requests with 503 "Server
Unavailable" errors.
But the best solution is probably to use AJAX. Load the page then make an ajax request to fill the repeater. That way you can have the nice "spinning" graphic or something else happening while you are waiting on the webservice.
Call the webservice, take the result, and bind it to your repeater.
If you can, you might also try to cache the information for a time on your side, if possible to help with overall performance.

Resources