S
Sunny
Hi all,
Does any one knows, if I create a thread in a method and start some
processing in it, what happens when this thread object goes out of
scope. Is it garbage collected (I assume yes, as it is a regular object
and there is no reference to it). If it is, what happens with the
executed code inside the thread? What kind of exceptions can I receive
(if any) and how to capture them (AppDomain.UnhandledException may help,
but how do I recognize that this is in the collected thread?).
This is a sample:
using System;
using System.Threading;
namespace Test {
public class Test {
static ManualResetEvent evnt = new ManualResetEvent(false);
static void CreateThread()
{
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.IsBackground = true;
t.Start();
}
static void ThreadMethod()
{
Console.WriteLine("Thread started");
evnt.Set();
while (true)
{
Console.WriteLine("From thread.");
Thread.Sleep(1000);
}
}
[STAThread]
public static void Main()
{
CreateThread();
evnt.WaitOne();
Console.WriteLine("press enter to GC");
Console.ReadLine();
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("press enter for exit");
Console.ReadLine();
}
}
}
The thread continues to run even after GC.Collect? Why? What holds a
reference?
And why TaskManager shows 6 threads running (before and after the
GC.Collect call) and 5 after that? I can count to 3 - the main one, GC
thread and my worker thread. What are the others?
Thanks
Sunny
Does any one knows, if I create a thread in a method and start some
processing in it, what happens when this thread object goes out of
scope. Is it garbage collected (I assume yes, as it is a regular object
and there is no reference to it). If it is, what happens with the
executed code inside the thread? What kind of exceptions can I receive
(if any) and how to capture them (AppDomain.UnhandledException may help,
but how do I recognize that this is in the collected thread?).
This is a sample:
using System;
using System.Threading;
namespace Test {
public class Test {
static ManualResetEvent evnt = new ManualResetEvent(false);
static void CreateThread()
{
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.IsBackground = true;
t.Start();
}
static void ThreadMethod()
{
Console.WriteLine("Thread started");
evnt.Set();
while (true)
{
Console.WriteLine("From thread.");
Thread.Sleep(1000);
}
}
[STAThread]
public static void Main()
{
CreateThread();
evnt.WaitOne();
Console.WriteLine("press enter to GC");
Console.ReadLine();
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("press enter for exit");
Console.ReadLine();
}
}
}
The thread continues to run even after GC.Collect? Why? What holds a
reference?
And why TaskManager shows 6 threads running (before and after the
GC.Collect call) and 5 after that? I can count to 3 - the main one, GC
thread and my worker thread. What are the others?
Thanks
Sunny