Reputation: 186
I created this test program to find out what happens when a timer callback thread returns but a newly created thread is still running. I will see "In Work" 10 times below, even though the local thread variable should no longer be in scope when timer_Elapsed returns. Setting the thread's "IsBackground" property to true had no effect.
Is this happening because the GC has not run yet? Is it therefore dangerous to assume that a thread created in this manner will complete, since the GC may run at any time and clean up the thread?
I'm aware this is a silly example, but I'm mostly interested in just understanding what's going on here so I know what to avoid. Thanks!
public class Program
{
static void Main(string[] args)
{
var timer = new Timer(500);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.AutoReset = false;
timer.Start();
Console.ReadLine();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("In timer elapsed. Kicking off a thread in new local thread and then immediately exiting.");
var thread = new Thread(Work);
thread.Start(); // but...this doesn't stop when the current thread exits!
Console.WriteLine("About to exit timer elapsed.");
}
static void Work()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("In Work");
Thread.Sleep(1000);
}
}
}
Upvotes: 1
Views: 256
Reputation: 1651
MSDN says that once a thread is started, it is not neccessary to retain the reference to the Thread object.
Upvotes: 2
Reputation: 44181
An executing thread holds a reference to itself. The GC will never terminate a thread which has gone out of scope elsewhere.
Upvotes: 3