views:

28

answers:

2

If I browse to an asp.net web page that has the following in the page load, how long will the thread continue to run for after I close the browser? I would assume it would just finish on its own, but I'm not sure if it will terminate when the session ends, or something like that.

protected void Page_Load(object sender, EventArgs e) {
    Thread T = new Thread(new ThreadStart(longRunningMethod));
    T.Start();
}

Thanks.

+2  A: 

The thread would stop when the code in the thread stops, i.e. whenever longRunningMethod() terminates.

This is why it can be a dangerous idea to start launching threads yourself within an application server, at least without managing their lifecycle (i.e. providing logic for the thread to be shut down after a certain time, making sure resources released, providing an upper bound on how many "worker threads" can run at once, etc.).

If each visit to a particular web page resulted in a separate thread being launched on the server, with the thread possibly running forever, eventually enough of those visits are going to bring the app server to it's knees.

matt b
For sure. This was an overly simplified example just to get a concept across. Thank you for the response.
Adam
+1  A: 

It's ok to use for shorter tasks. I have a reporting system that does this so that while a user gets the first part of the report quickly, the stats can be generated separately so that they are ready by the time the client gets to them. For longer running processes (in my case longer than 30s) you will want to leverage a service of some sort and add your task to a queue.

You also need to consider that if the application pool recycles it will terminate your threads so that provides an added incentive to move those threads elsewhere.

Lastly you will want to have some way to indicate that your process finished. Consider how you will know when the thread finishes so that if you try the request again you don’t generate the same set of data that might already be processing.

Middletone