ProcessExit
次のイベントを使用できますAppDomain
。
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
// do some work
}
static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
Console.WriteLine("exit");
}
}
アップデート
以下は、空の「メッセージ ポンプ」が別のスレッドで実行されている完全なサンプル プログラムです。これにより、ユーザーはコンソールで終了コマンドを入力して、アプリケーションを正常に終了できます。MessagePump のループの後、スレッドが使用するリソースを適切な方法でクリーンアップする必要があるでしょう。いくつかの理由から、ProcessExit よりもそこで行う方が良いです:
- クロススレッドの問題を回避します。外部 COM オブジェクトが MessagePump スレッドで作成された場合は、そこで処理する方が簡単です。
- ProcessExit には制限時間 (既定では 3 秒) があるため、クリーンアップに時間がかかる場合、そのイベント ハンドラー内で実行すると失敗する可能性があります。
コードは次のとおりです。
class Program
{
private static bool _quitRequested = false;
private static object _syncLock = new object();
private static AutoResetEvent _waitHandle = new AutoResetEvent(false);
static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
// start the message pumping thread
Thread msgThread = new Thread(MessagePump);
msgThread.Start();
// read input to detect "quit" command
string command = string.Empty;
do
{
command = Console.ReadLine();
} while (!command.Equals("quit", StringComparison.InvariantCultureIgnoreCase));
// signal that we want to quit
SetQuitRequested();
// wait until the message pump says it's done
_waitHandle.WaitOne();
// perform any additional cleanup, logging or whatever
}
private static void SetQuitRequested()
{
lock (_syncLock)
{
_quitRequested = true;
}
}
private static void MessagePump()
{
do
{
// act on messages
} while (!_quitRequested);
_waitHandle.Set();
}
static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
Console.WriteLine("exit");
}
}