开发者

How to terminate a thread which has spawned another thread which is sleeping? [closed]

开发者 https://www.devze.com 2023-01-03 03:13 出处:网络
This question is unlikely to help any future visitors; it is only r开发者_StackOverflowelevant to a small geographic area, a specific moment in time,or an extraordinarily narrow situation that is
This question is unlikely to help any future visitors; it is only r开发者_StackOverflowelevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

I have a long running thread made from Thread.Start(). It spawns a background thread using QueueUserWorkItem which sleeps most of the time.

Then the class-owner get disposed I call thread1.Join() but naturally it doesnt return because its child background thread is sleeping.

What would be the right solution to gracefully terminate a thread which has other threads with little hassle?


After I wrote the question I suddenly realised that I probably had a mental block when I did this part.

In first place the thread didnt want to terminate not because of the background thread. But for another reason.

In second - I had to use timer instead because I held a thread for no reason - only to wait for an event which happens once a day!

It was very stupid of me :) sorry.


It is usually good to use Thread Pool thread for a short term thread. If you need a background thread that will run for long time use a new instance of Thread and set its Background property to true.


If you use .Abort, it will cause a ThreadAbortException on the applicable thread - respond to this as gracefully as you can. You can also use Begin/EndCriticalRegion.


I'm not sure if it's the right solution, but I normally make the background thread sleep for only short periods of time and then wake up to check the status and then either exit, do some work or go to sleep again. Might not be good if you're looking for absolute performance, but at least for most non server apps I would have thought it would be ok.

0

精彩评论

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