在.NET中,在此代码之后,什么机制阻止Thread对象被垃圾回收?
new Thread(Foo).Start();
GC.Collect();
Run Code Online (Sandbox Code Playgroud)
是的,可以安全地假设某些东西有对线程的引用,我只是在徘徊究竟是什么.出于某种原因,Reflector没有向我展示System.Threading,所以我不能自己挖掘它(我知道MS发布了.NET框架的源代码,我只是没有它的方便).
我有以下代码(为了便于阅读而减少):
主类:
public StartProcess()
{
Thinker th = new Thinker();
th.DoneThinking += new Thinker.ProcessingFinished(ThinkerFinished);
th.StartThinking();
}
void ThinkerFinished()
{
Console.WriteLine("Thinker finished");
}
Run Code Online (Sandbox Code Playgroud)
思想家班级:
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); …Run Code Online (Sandbox Code Playgroud)