2015-09-07 68 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.