Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to unsubscribe from an event in a c# metro application?

I have subscribed various event in OnNavigatedTo like

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    Loaded += Screen_Loaded;
}

I haven't unsubscribed this event. Does it cause any memory issue when this page is not needed??

like image 844
Inder Kumar Rathore Avatar asked Dec 11 '12 04:12

Inder Kumar Rathore


2 Answers

No. In this case you do not need to unsubscribe to avoid memory leaks. The reason is that you subscribe to an event on this. The garbage collector must identify this and free the object.

But, I would for other reasons still unsubscribe. For example having balanced resources makes the code easier to read. Also what if the OnNavigatedTo gets called twice? (Don't actually know if this can even happen) Then you'll have two subscriptions to the same method. Some would argue that unsubscribing in this scenario is redundant code and remove it. Although correct as such I would oppose such arguments.

You can try this short snippet to try it out yourself. Note: Never user finalizers or GC.Collect() except for learning about the GC like in this example.

public class Program
{
    private class Foo
    {
        public event EventHandler FooChanged;

        ~Foo()
        {
            Console.WriteLine("Foo was collected");
        }

        public void Bar()
        {
            FooChanged += UpdateUI;
        }

        private void UpdateUI(object sender, EventArgs e)
        {
        }
    }

    public static void Main(string[] args)
    {
        var foo = new Foo();
        foo.Bar();
        foo = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine("End of program");
        Console.ReadKey();
    }
}
like image 137
vidstige Avatar answered Oct 08 '22 02:10

vidstige


Yes you do have to unsubscribe from some event which might be automatically fired in a metro app

For Example :

Events such as

Window.Current.SizeChanged += Current_SizeChanged;

void Current_SizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
{
    //your code block contining various objects and logic
}

These events are not controlled by you as they are fire in the background. Any event which might not be related to a particular page (suppose the above event is initilized in the OnNavigatedTo Event) then you have to unsubscribe from it in events like OnNavigatedFrom

For further clarification initialize this event

Window.Current.SizeChanged += Current_SizeChanged;

and just keep a break point and change the size of the window change from landscape to snapped mode and this event will fire unless you have not unsubscribed from the event.

like image 2
Anobik Avatar answered Oct 08 '22 01:10

Anobik