Suppose I have a code as follows:
int Main()
{
if (true)
{
new Thread(()=>
{
doSomeLengthyOperation();
}).Start();
}
while (true)
{
//do nothing
}
}
There are 2 threads, I'm going to call the Main thread the thread that is executing the Main() function, and the thread being new'ed up inside the "if" test as Thread A.
My question is, when does Thread A get destroyed? Will doSomeLenghtyOperation() be able to run into completion?
Since there are no references pointing at Thread A, will it be marked as a candidate for garbage collection:
All the examples I see are the Main() holding the reference, and then Main thread waiting to join with thread A before exiting. I'm curious what the lifetime of the code above is.
Thanks in advance!
The Thread
object will be eligible for garbage collection as soon as it's not used any more, i.e. immediately after calling the Start
method. (It will however not be collected immediately, as the garbage collector runs at specific times.)
The actual thread however is not relying on the Thread
object, and will continue to run even if the Thread
object is collected.
If the thread is still running when the main method exits, the application will not end until the thread completes, unless you have marked the thread to be a background thread.