views:

54

answers:

4

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?

+1  A: 

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.

Itay
No the background thread sleeps most of the time.
Bobb
@Bobb, in this case, you are still using the thread pool's thread for a long time, even if it is only sleeping. this should be avoided.
Chris O
yes. see my "answer" below. I got that too a bit later :)
Bobb
A: 

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.

Adam
ThreadAbort is a horrendous way to end a thread. http://www.bluebytesoftware.com/blog/2009/03/13/ManagedCodeAndAsynchronousExceptionHardening.aspx
Alan
http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation
Alan
http://msmvps.com/blogs/senthil/archive/2008/12/17/the-dangers-of-thread-abort.aspx
Alan
And you get the hint.
Alan
I agree with Alan.
Bobb
A: 

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.

Bobb
A: 

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.

ho1