oliver
oliver

Reputation: 2891

Anonymous method as event handler

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;
    }
}

Upvotes: 0

Views: 1147

Answers (1)

Jazimov
Jazimov

Reputation: 13282

To unregister all event handlers for an event that you own, simply use this code:

isoDataTemp.CheckExecution = null;

Note that this works for anonymous and non-anonymous event handlers.

From your example, you can add this code to your OnFormClosing event, to ensure that events assign to your isoDataTemp object are properly and completely removed.

Note that if the isoDataTemp object is a child object of the form object, then it will be removed when your Form object is destroyed and will be garbage-collected along with the destroyed Form object instance, as expected.

Upvotes: 1

Related Questions