Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should one always keep a reference to a running Thread object in C#?

Or is it okay to do something like this:

new Thread( new ThreadStart( delegate { DoSomething(); } ) ).Start();

?

I seem to recall that under such a scenario, the Thread object would be garbage collected, but the underlying OS thread would continue to run until the end of the delegate passed into it. I'm basically looking for ThreadPool functionality, but don't want the threads to be background threads (i.e. I want them to keep the app alive).

Update:
According to Jason, the CLR actually keeps an internal reference to the Thread object, while running, so it won't be garbage collected until the thread exits.

like image 967
devios1 Avatar asked Dec 24 '08 04:12

devios1


1 Answers

I have generally found that if I need to directly start a new thread the way you are in your example, rather than grabbing one from the thread pool, then it is a long running thread and I will need a reference to it later to kill it, monitor it, etc. For short run threads like invoking IO on a background thread, etc, I always use a thread pool thread (usually indirectly through a someDelete.BeginBlah(...) method call). When using a thread pool thread like this I prefer to NOT keep a reference around. I don't know if another programmer might inappropriately use a reference to that thread. If I don't need a reference, I don't keep it around to clutter up code.

Edit: To answer your edit about threads being garbage collected, this will not occur while the thread is running. The CLR keeps a reference to every running thread. The object representing the thread will NOT be collected.

like image 111
Jason Jackson Avatar answered Sep 26 '22 01:09

Jason Jackson