I have the following code:
new Thread(new ThreadStart(delegate()
{
while (true)
{
//something
}
})).Start();
Can garbag
The thread won't be collected, because each running, waiting or suspended thread is itself used by the GC to decide what is alive (trace everything in every thread's stack, trace everything referenced by all of those objects, then everything referenced by those, and so on, and you've identified everything that can't be garbage collected).
The thread could end, if it was a background thread, because then it'll be actively shut down when all other threads in the process finish. Otherwise the only thing that'll cause it to die is the process being actively exited, an exception (including ThreadAbortException
) or it breaking out of the while
loop itself.
There's a case that's comparable in some ways, that may be what you are thinking of:
var timer = new System.Threading.Timer(someCallback, null, new TimeSpan(0, 0, 5), new TimeSpan(0, 0, 5));
int someResult = doingSomethingElse();
doSomethingElseThatTakesLongerThan5Seconds();
This is another piece of code that causes another thread of execution to do something. In this case, the timer can indeed be garbage collected before the run, during one of the runs, or pretty much any time after the constructor returns.
The important thing here is that there isn't an individual thread for the timer, and the thread doesn't even "know" about the timer object. Since the last access of the object has since happened, it's eligible for collection. This is different to the matter of an individual thread that is running (or waiting, etc.).
The CLR keeps track of all running threads. As long as there are references to objects they won't be garbage collected. And since the CLR keeps a reference to all running threads the GC won't touch them.
No; running threads count as roots. A running thread will not be collected, nor will anything referenced by the active part(s) of the stack for that thread.
All running timer, threads, thread pool and tasks are marked as root. So they will be garbage collected only when they're done (finished executing) or will be deleted when the application closes.