简体   繁体   English

安全退出控制台应用程序?

[英]Safely exit console-application?

I have a console application that will be ran on the weekends. 我有一个控制台应用程序,它将在周末运行。 And when I come back into work I will need to safely terminate it. 当我重新开始工作时,将需要安全地终止它。

It is running a loop and modifying files by moving them, and updating a database. 它正在运行一个循环,并通过移动文件和更新数据库来修改文件。

I cannot just simply Ctrl-Z to exit it I am assuming as this could stop the program in the middle of working on a file? 我不能简单地按Ctrl-Z退出它,因为这可能会在文件处理过程中使程序停止?

Is there a safe way for me to say press the 'c' key to set my runLoop boolean to false so this would exit my loop properly or is there a better way? 我有没有安全的方法可以说按一下'c'键将runLoop boolean设置为false ,这样就可以正确退出循环,还是有更好的方法?

static void Main(string[] args)
{
     bool runLoop = true;

     while (runLoop)
     {
          // bunch of code
          // moving files, updating database.
     }
}

What is a safe way to terminate this loop and ensure the currently running file will be finished successfully? 有什么安全的方法可以终止此循环并确保当前运行的文件将成功完成?

You can easily add a handler to an event exposed to you for when that command is pressed and use it to signal cancellation: 您可以轻松地将处理程序添加到按下该命令时向您公开的事件,并使用它来表示取消:

bool runLoop = true;

ManualResetEvent allDoneEvent = new ManualResetEvent(false);
Console.CancelKeyPress += (s, e) =>
{
    runLoop = false;
    allDoneEvent.WaitOne();
};

int i = 0;
while (runLoop)
{
    Console.WriteLine(i++);
    Thread.Sleep(1000);  //placeholder for real work
}

//for debugging purposes only
Console.WriteLine();
Console.WriteLine("press any key to exit . . .");
Console.ReadKey(true);

allDoneEvent.Set();

Note that the entire process will be killed when that event handler finishes, so you also need to ensure that that event handler is kept running until the rest of the program is able to finish gracefully. 请注意,当该事件处理程序完成时,整个过程将被终止,因此,您还需要确保该事件处理程序一直运行,直到程序的其余部分能够正常完成为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM