如何在请求服务停止时收到通知

时间:2010-08-13 11:52:07

标签: c# windows-services

我从http://tech.einaregilsson.com/2007/08/15/run-windows-service-as-a-console-program/

获得了以下代码

在控制台模式下运行时,我希望在请求服务停止时收到通知,而不是等待用户输入。 (我的意思是用户要求通过Ctrl + C或关闭控制台来停止程序)

当作为服务工作时,OnStop在停止请求时被调用是微不足道的,但是如何实现变通方法以便在控制台模式下工作时也可以得到通知。

那么我可以订阅任何事件通知或任何会员功能等吗?

提前致谢。
最好的问候,
-胜利者

using System;
using System.ServiceProcess;
public partial class DemoService : ServiceBase
{
    static void Main(string[] args)

    {
        DemoService service = new DemoService();

        if (Environment.UserInteractive) // Console mode
        {
            service.OnStart(args);
            Console.WriteLine("Press any key to stop program");

            Console.Read();

            service.OnStop();
        }
        else
        {
            ServiceBase.Run(service);
        } 
    }

    public DemoService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        // TODO: Add code here to start your service.
    }
    protected override void OnStop()
    {
        // TODO: Add code here to perform any tear-down

        //necessary to stop your service.
    }
}

1 个答案:

答案 0 :(得分:1)

我认为你正在寻找CancelKeyPress事件。见http://msdn.microsoft.com/en-us/library/system.console.cancelkeypress.aspx