开发者

Thread in Code behind

开发者 https://www.devze.com 2023-01-04 06:29 出处:网络
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 li

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?


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.


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.


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消