1

Windows サービスがクラッシュし、いくつかの回復オプションが原因で自動的に再起動されたとします。これが発生するたびにネットワークアクションを実行する(シャットダウンのアラートを送信する)プログラム(C#)でコードを実行したいと考えています。

適用できるイベントや、その発生後に実行できるコードはありますか?

ありがとう!

4

2 に答える 2

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"));
    }

    //...
}

これにより、ファイルがレジストリ エントリまたはデータベース内のレコードと簡単に交換される可能性があります。

于 2016-02-22T21:05:11.733 に答える
2

例外が発生したスレッドに関係なく発生する以下のイベントにサブスクライブできます。

AppDomain.CurrentDomain.UnhandledException

実装例

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

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
 // log the exception ...
}
于 2016-02-22T20:58:22.823 に答える