Ho il codice seguente (abbattuto per migliorare la leggibilità):Will .Net Garbage Colleziona un oggetto a cui non si fa riferimento, ma ha un thread che sta funzionando?
principale Classe:
public StartProcess()
{
Thinker th = new Thinker();
th.DoneThinking += new Thinker.ProcessingFinished(ThinkerFinished);
th.StartThinking();
}
void ThinkerFinished()
{
Console.WriteLine("Thinker finished");
}
Pensatore Classe:
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();
}
}
Quello che originariamente previsto per accadere era che il gestore di eventi nella classe principale impedirebbe al Thinker di essere raccolto dalla spazzatura.
Apparently this isn't the case.
Ora mi chiedo se la garbage collection si verificherà indipendentemente dal fatto che questo thread sia "occupato" o meno. In altre parole, c'è la possibilità che venga raccolto dei rifiuti prima che sia scaduto il timeout di 5 secondi?
Per dirla in altro modo, è possibile che il garbage collector raccolga il mio pensatore prima che l'elaborazione sia terminata?
Quando si verifica l'evento trascorso sul timer, avviene su una nuova discussione. Forse è di questo che sta parlando. http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx – Joe
Scusate, non ero chiaro: il chunk commentato è davvero più importante di quanto gli abbia dato credito. Cercherò di aggiornare – Damovisa
Inoltre, quello che Joe K ha detto - il Timer stesso che presumevo avrebbe funzionato su un thread diverso. L'evento Elapsed torna sicuramente su un altro thread. – Damovisa