LeBrown Jones
LeBrown Jones

Reputation: 917

Do I HAVE TO unsubscribe from all events in all cases?

For example, if I have a UserControl or a Page that creates its own event in its code-behind file, when that Page or control unloads, do I have to make sure its events are unsubscribed from? I mean there are no external subscriptions. Every subscriber is self-contained, so I would THINK that it wouldn't matter once the control is unloaded:

public sealed partial class MyPage : Page
{
    public MyPage()
    {
        this.Unloaded += Page_Unloaded;
        this.Tapped += Page_Tapped;
    }

    private void Page_Tapped(object sender, TappedRoutedEventArgs e)
    {
        // Do some work here.
    }

    private void Page_Unloaded(object sender, RoutedEventArgs e)
    {
        // Is the following appropriate and REQUIRED?

        this.Unloaded -= Page_Unloaded;
        this.Tapped -= Page_Tapped;
    }
}

Upvotes: 2

Views: 369

Answers (2)

Mosern1977
Mosern1977

Reputation: 19

No, under normal circumstances - unloading is not required.

However, if you create your own static delegates, then you must remember to unload them - as they are not removed when your instance goes out of scope.

Upvotes: 2

Scott Hannen
Scott Hannen

Reputation: 29207

No, you do not need to unsubscribe. You are not creating any additional references to MyPage. When each request is complete and each instance of MyPage goes out of scope there are no references to the instance that need to be removed.

Upvotes: 3

Related Questions