我尝试停止控制台应用程序关闭但它在所有功能完成之前关闭。示例停止到90000然后控制台关闭..我想要它首先完成所有作业然后关闭控制台。对不起我的英文不好。
示例:
private delegate bool EventHandler(CtrlType sig);
private enum CtrlType
{
CTRL_BREAK_EVENT = 1,
CTRL_C_EVENT = 0,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
private static EventHandler delegate0_0;
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(Program.EventHandler handler, bool add);
private const int MF_BYCOMMAND = 0x00000000;
public const int SC_CLOSE = 0xF060;
static void Main(string[] args)
{
Program.delegate0_0 = (Program.EventHandler)Delegate.Combine(Program.delegate0_0, new Program.EventHandler(Program.smethod_1));
Program.SetConsoleCtrlHandler(Program.delegate0_0, true);
Console.ReadKey(true);
}
private static bool smethod_1(CtrlType enum0_0)
{
for (int i = 0; i < 10000000; i++)
{
Console.WriteLine(i);
}
return true;
}
答案 0 :(得分:1)
在句柄上使用EventWaitHandle,以便等待它发出信号。
您正在使用非托管句柄,因此这是WIN32的WaitForSingleObject(HANDLE h, DWORD duaration();
所以这是C#代码:
EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.ManualReset);
handle.SafeWaitHandle = new Microsoft.Win32.SafeHandles.SafeWaitHandle(yourHandle,true);
handle.WaitOne();
true
创建中的SafeWaitHandle
表示它应该与终结器一起清理。
答案 1 :(得分:0)
您可以通过让程序在程序结束时等待用户输入来停止它:
Console.ReadLine();
或
Console.ReadKey();
原帖: How to stop C# console applications from closing automatically?