2
votes

I have a class that is assigning itself to an event:

public MainMenuButton()
{
     this.DefaultStyleKey = typeof(MainMenuButton);
     (App.Current as App).ApplicationLanguageChange += Localize;
}

And on destructor i do this:

~MainMenuButton()
{
    (App.Current as App).ApplicationLanguageChange -= Localize;
}

When on emulator i do a longpress on back button and close the app - the destructor throws an error:

An unhandled exception of type 'System.Exception' occurred in myapplication.WindowsPhone.exe

Additional information: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

1

1 Answers

2
votes

When on emulator i do a longpress on back button and close the app - the destructor throws an error

You cannot access any managed resources from a finalizer. There is no guarantee that any of them will still be alive. If all you're doing is de-registering from an event, you don't need that finalizer at all, as your app is about to close anyway.

The docs say:

Finalize operations have the following limitations:

  • The exact time when the finalizer executes is undefined. To ensure deterministic release of resources for instances of your class, implement a Close method or provide a IDisposable.Dispose implementation.

  • The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already been finalized when the finalizer of Object A starts.

  • The thread on which the finalizer runs is unspecified.