How to terminate a thread which has spawned another thread which is sleeping? [closed]
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.
精彩评论