在.NET中,是否有一个方法(如事件)用于检测控制台应用程序何时退出?我需要清理一些线程和COM对象。
我正在从控制台应用程序运行一个没有表单的消息循环。我正在使用的DCOM组件似乎要求应用程序泵消息。
我尝试为Process.GetCurrentProcess.Exited和Process.GetCurrentProcess.Disposed添加处理程序。
我还尝试向Application.ApplicationExit和Application.ThreadExit事件添加处理程序,但它们没有触发。也许那是因为我没有使用表格。
答案 0 :(得分:60)
您可以使用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");
}
}
<强>更新强>
这是一个完整的示例程序,在单独的线程上运行一个空的“消息泵”,允许用户在控制台中输入一个quit命令来正常关闭应用程序。在MessagePump中循环之后,您可能希望以一种很好的方式清理线程使用的资源。这样做比在ProcessExit中做得更好有几个原因:
以下是代码:
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");
}
}
答案 1 :(得分:26)
这是一个完整的,非常简单的.Net解决方案,适用于所有版本的Windows。只需将其粘贴到一个新项目中,运行它并尝试CTRL-C来查看它如何处理它:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace TestTrapCtrlC{
public class Program{
static bool exitSystem = false;
#region Trap application termination
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
private delegate bool EventHandler(CtrlType sig);
static EventHandler _handler;
enum CtrlType {
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
private static bool Handler(CtrlType sig) {
Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown");
//do your cleanup here
Thread.Sleep(5000); //simulate some cleanup delay
Console.WriteLine("Cleanup complete");
//allow main to run off
exitSystem = true;
//shutdown right away so there are no lingering threads
Environment.Exit(-1);
return true;
}
#endregion
static void Main(string[] args) {
// Some biolerplate to react to close window event, CTRL-C, kill, etc
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
//start your multi threaded program here
Program p = new Program();
p.Start();
//hold the console so it doesn’t run off the end
while(!exitSystem) {
Thread.Sleep(500);
}
}
public void Start() {
// start a thread and start doing some processing
Console.WriteLine("Thread started, processing..");
}
}
}
答案 2 :(得分:17)
应用程序是一个服务器,只需运行直到系统关闭或接收到Ctrl + C或控制台窗口关闭。
由于应用程序的特殊性,“优雅地”退出是不可行的。 (可能是我可以编写另一个会发送“服务器关闭”消息的应用程序,但这对于一个应用程序来说是过度的,而且在某些情况下仍然不够,例如当服务器(实际操作系统)实际关闭时。)
由于这些情况,我添加了一个“ConsoleCtrlHandler”,我停止了我的线程并清理了我的COM对象等......
Public Declare Auto Function SetConsoleCtrlHandler Lib "kernel32.dll" (ByVal Handler As HandlerRoutine, ByVal Add As Boolean) As Boolean
Public Delegate Function HandlerRoutine(ByVal CtrlType As CtrlTypes) As Boolean
Public Enum CtrlTypes
CTRL_C_EVENT = 0
CTRL_BREAK_EVENT
CTRL_CLOSE_EVENT
CTRL_LOGOFF_EVENT = 5
CTRL_SHUTDOWN_EVENT
End Enum
Public Function ControlHandler(ByVal ctrlType As CtrlTypes) As Boolean
.
.clean up code here
.
End Function
Public Sub Main()
.
.
.
SetConsoleCtrlHandler(New HandlerRoutine(AddressOf ControlHandler), True)
.
.
End Sub
此设置似乎完美无缺。对于同样的事情,这里有一些link到一些C#代码。
答案 3 :(得分:8)
对于CTRL + C案例,您可以使用:
// Tell the system console to handle CTRL+C by calling our method that
// gracefully shuts down.
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Console.WriteLine("Shutting down...");
// Cleanup here
System.Threading.Thread.Sleep(750);
}
答案 4 :(得分:1)
如果您正在使用控制台应用程序并且正在发送消息,那么您是否不能使用WM_QUIT消息?
答案 5 :(得分:-1)
作为一个很好的例子可能值得navigate to this project看看如何以语法方式处理退出流程或在VM found in here
的此代码段中处理 ConsoleOutputStream = new ObservableCollection<string>();
var startInfo = new ProcessStartInfo(FilePath)
{
WorkingDirectory = RootFolderPath,
Arguments = StartingArguments,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
ConsoleProcess = new Process {StartInfo = startInfo};
ConsoleProcess.EnableRaisingEvents = true;
ConsoleProcess.OutputDataReceived += (sender, args) =>
{
App.Current.Dispatcher.Invoke((System.Action) delegate
{
ConsoleOutputStream.Insert(0, args.Data);
//ConsoleOutputStream.Add(args.Data);
});
};
ConsoleProcess.Exited += (sender, args) =>
{
InProgress = false;
};
ConsoleProcess.Start();
ConsoleProcess.BeginOutputReadLine();
}
}
private void RegisterProcessWatcher()
{
startWatch = new ManagementEventWatcher(
new WqlEventQuery($"SELECT * FROM Win32_ProcessStartTrace where ProcessName = '{FileName}'"));
startWatch.EventArrived += new EventArrivedEventHandler(startProcessWatch_EventArrived);
stopWatch = new ManagementEventWatcher(
new WqlEventQuery($"SELECT * FROM Win32_ProcessStopTrace where ProcessName = '{FileName}'"));
stopWatch.EventArrived += new EventArrivedEventHandler(stopProcessWatch_EventArrived);
}
private void stopProcessWatch_EventArrived(object sender, EventArrivedEventArgs e)
{
InProgress = false;
}
private void startProcessWatch_EventArrived(object sender, EventArrivedEventArgs e)
{
InProgress = true;
}