2016-02-22 18 views

回答

3

在這種情況我會做的是,而不是當程序失敗時寫出來的東西,讓程序寫出一些如果它檢測到乾淨關閉正在完成,那麼它將永久性存儲的記錄類型刪除。

public partial class MyAppService : ServiceBase 
{ 
    protected override void OnStart(string[] args) 
    { 
     if(File.Exists(Path.Combine(Path.GetTempPath(), "MyAppIsRunning.doNotDelete")) 
     { 
      DoSomthingBecauseWeHadABadShutdown(); 
     } 
     File.WriteAllText(Path.Combine(Path.GetTempPath(), "MyAppIsRunning.doNotDelete"), ""); 
     RunRestOfCode(); 
    } 

    protected override void OnStop() 
    { 
     File.Delete(Path.Combine(Path.GetTempPath(), "MyAppIsRunning.doNotDelete")); 
    } 

    //... 
} 

這可以很容易地將文件換出與數據庫中的一個註冊表項或記錄。

2

您可以訂閱以下事件時會觸發無論在哪個線程發生異常..

AppDomain.CurrentDomain.UnhandledException

樣品實施

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); 

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
{ 
// log the exception ... 
} 
相關問題