user1613898
user1613898

Reputation: 1

Must one unsubscribe to an event as a delegate?

I want to do use this little context menu when User presses a button:

private ContextMenuStrip TaskMenu()
{
    ContextMenuStrip Result = new ContextMenuStrip();
    Result.Items.Add("Select task to start:");
    Result.Items.AddRange(
        System.IO.Directory.GetFiles("C:\\Settings\\Tasks", true), "*.tsk")
            .Select(qF => new ToolStripMenuItem(System.IO.Path.GetFileNameWithoutExtension(qF)) { Tag = qF, Checked = qF == this.TaskFile })
            .ToArray());
    Result.Items.Add("Cancel");
    Result.ItemClicked += new ToolStripItemClickedEventHandler(
        delegate(object s, ToolStripItemClickedEventArgs ev) { StartScan((string)ev.ClickedItem.Tag); });
    return Result;
}

But, I shouldn't because I never unsubscribe the event. Right?

Upvotes: 0

Views: 114

Answers (2)

James
James

Reputation: 82096

I shouldn't because I never unsubscribe the event, Right?

If you need your event to be unhooked at some point, then this isn't the correct approach. The way around this is to take a reference to the handler so you can unsubscribe it later.

If you are worried purely from a memory leak point of view, then don't. When your ContextMenuStrip is GC'd so will your delegate.

Upvotes: 0

Jon
Jon

Reputation: 437326

There should be no issue here. Result is created inside the method, so there is no possibility of attaching the same event handler twice.

When the last reference to Result goes out of scope it becomes eligible for garbage collection. As long as nothing outside this method keeps a permanent reference to Result, when garbage is collected both it and the reference to the delegate will be cleaned up.

Upvotes: 1

Related Questions