Edit: this question is not about how to unsubscribe from events because I know how to do that if I want to. The question is about if there is a conflict with garbage collection in my specific scenario.
In some code I wrote a while ago I registered an event (CheckExecution
, owned by isoDataTemp
, see code below) by means of an anonymous method. But now it has come to my mind that assigning an anonymous method to an event is pretty evil because there is no way to unregister the method from the event, right? I once had a problem with an object that could not be garbage collected because an event was still pointing to it.
So I wonder if I can get into trouble with it here. My spontaneous reaction is "no, because the anonymous method belongs to the MainForm and this has longer lifetime than its isoDataTemp
member". But I am not sure. What about closures? Does the anonymous method belong to MainForm at all. I am confused...
public partial class MainForm : Form
{
// ...
void BackgroundWorkerISOAnalysisDoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
int prog = 0;
isoDataTemp.CheckExecution += () =>
{
prog += 12;
if (prog > 100) prog = 100;
worker.ReportProgress(prog);
return !worker.CancellationPending;
};
isoDataTemp.Analyze();
if (worker.CancellationPending) e.Cancel = true;
}
}