【问题标题】:Gracefully (and controlled) exit from .NET console application从 .NET 控制台应用程序优雅地(和受控地)退出
【发布时间】:2018-11-21 14:06:08
【问题描述】:

我需要将 C# windows 服务 (.NET Framework 4.6.1) 转换为控制台应用程序。所以这个应用程序没有真正的交互界面。 在 Windows 服务应用程序中,我有 OnStop() 方法可以在终止之前执行我需要的操作...并退出。

当然,我可以使用众所周知的名称创建一个文件,并在控制台应用程序中定期检查该文件,但在我看来这是一个老式的解决方案。

是否有“最佳实践”要求控制台应用程序在有时间完成当前处理的情况下正常终止?

【问题讨论】:

  • 在控制台检查Ctrl-C,当检测到时,运行OnStop()方法?
  • 是的...这是一个简单直接的解决方案,谢谢。我在link 找到了一个简单的代码

标签: c# .net windows-services console-application


【解决方案1】:

所以我找到的解决方案有以下代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        private static bool keepRunning = true;

        public static void Main(string[] args)
        {
            Console.WriteLine("Main started");

            Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e) {
                e.Cancel = true;
                keepRunning = false;
            };

            while (keepRunning)
            {
                Console.WriteLine("Doing really evil things...");

                System.Threading.Thread.Sleep(3000);
            }

            Console.WriteLine("Exited gracefully");
        }
    }
}

【讨论】:

    猜你喜欢
    • 2013-07-21
    • 1970-01-01
    • 2010-11-10
    • 2014-12-11
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多