2015-09-07 72 views
2

我有一类本身就是一个事件分配:析构函数的碰撞

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

而且在析构函数我这样做:

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

当在模拟器我做了长按在后退按钮和关闭应用程序 - 析构函数抛出一个错误:

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

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

回答

2

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

您无法从终结器访问任何受管资源。不能保证他们中的任何一个仍然活着。如果你所做的只是从一个事件中注销,那么根本就不需要那个终结器,因为你的应用即将关闭。

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.