views:

54

answers:

3

Hi,

I have a aspx.cs page and a corresponding aspx page for it. When this page is loaded, and on a button event, I have created a thread which runs for sometime and then exits. I would like to know who is the parent of this thread.

Lets say the thread is running and I close this page, will this thread exit?

I did this but the thread kept running.

Actually I want to do is cleanup the task at the time the page is closed by the user.

Is w3wp parent of this thread? If no then, if I close this page who will become the parent?

A: 

Running threads on behalf of users is not a recommended practice. I recommend looking into asynchronous pages if possible for your site.

If you really do need a thread, then you'd have to create a thread lookup by session id (e.g., a Dictionary<string, Thread>). When you start the thread, store it in the dictionary (the current session id is Session.SessionID). When the session ends (Session_OnEnd in Global.aspx), tell the thread to stop and remove it from the dictionary.

Remember to lock your dictionary object.

Stephen Cleary
A: 

Since your browser and your webserver are in no way connected other than the odd few times you actually do a request, ASP.NET or IIS can not detect when your browser window is closed. The only thing you could do is detect the session ending. Since you indicate you only want to do clean-up and since I'm not sure if it's a good idea to do a long running operation in your Session_OnEnd handler, so you might want to use the thread pool:

protected void Session_OnEnd(object sender, EventArgs e)
{
    ThreadPool.QueueUserWorkItem(CleanUpSession, myStateObject);
}

private void CleanUpSession(object state)
{
    // do your clean-up here
}
ErikHeemskerk
A: 

Threads don't have parents. In particular, the "death" of a parent means nothing to them.

A problem you may encounter is that your thread method may depend on data that is specific to the page or to the request. Anything that depends on HttpContext will be a problem, because the thread can still be running after the request is over and HttpContext is no longer valid. The same goes for having the thread depend on anything on the page, since the page is destroyed after the request is complete.

See "Wicked Code: Asynchronous Pages in ASP.NET 2.0" to learn a good pattern for asynchronous actions in ASP.NET pages. This is how pages are meant to interact with the async world.

John Saunders