我有以下的code(减少以增强可读性):
I have the following code (cut down for readability):
主类:
public StartProcess()
{
Thinker th = new Thinker();
th.DoneThinking += new Thinker.ProcessingFinished(ThinkerFinished);
th.StartThinking();
}
void ThinkerFinished()
{
Console.WriteLine("Thinker finished");
}
思想家类:
public class Thinker
{
private System.Timers.Timer t;
public delegate void ProcessingFinished();
public event ProcessingFinished DoneThinking;
BackgroundWorker backgroundThread;
public Thinker() { }
public StartThinking()
{
t = new System.Timers.Timer(5000); // 5 second timer
t.AutoReset = false;
t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
t.Start();
// start a background thread to do the thinking
backgroundThread = new BackgroundWorker();
backgroundThread.DoWork += new DoWorkEventHandler(BgThread_DoWork);
backgroundThread.RunWorkerAsync();
}
void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
DoneThinking();
}
BgThread_DoWork(object sender, DoWorkEventArgs e)
{
// work in here should go for much less than 5 seconds
// it will die if it doesn't
t.Stop();
DoneThinking();
}
}
我原本期望发生的是,在主类的事件处理程序将prevent的思想家被垃圾收集。
What I originally expected to happen was that the event handler in the main class would prevent the Thinker from being garbage collected.
Apparently不是这种情况的
我现在不知道是否会发生垃圾收集无论线程是否是忙还是不行。换句话说,有没有它会被垃圾回收前5秒超时已过期的机会吗?
I'm now wondering whether garbage collection will occur regardless of whether this thread is "busy" or not. In other words, is there a chance it will be garbage collected before the 5 second timeout has expired?
要换个说法,是有可能的垃圾收集器收集我的思想者在它之前完成处理?
To put it another way, is it possible for the garbage collector to collect my Thinker before it's finished processing?
没有,一个线程是活的,只要它被引用,并且在运行被认为是引用(任何线程IIRC一个正在运行的线程注册其协议栈考虑作为GC根,而且堆栈将引用的线程)。
No, a thread is considered live as long as it is referenced, and any thread that is running is considered to be referenced (IIRC a running thread registers its stack as a GC root, and that stack will reference the thread).
这是说我在看你的榜样,我不明白的地方,你相信一个线程被催生?
That said i'm looking at your example and i don't understand where you believe a thread is being spawned?