启动然后非常快地停止Windows服务,OnStop方法没有调用

时间:2016-06-07 04:05:08

标签: windows c#-4.0 windows-services

我正在做一个Windows服务(称之为SampleService),一切都很好。当我开始然后通过Windows服务管理工具(service.msc)停止服务时,它运行正常。

但我的服务将是另一个应用程序请求启动和停止。所以在这种情况下我不会使用Windows服务管理工具。

这是我的服务工具。

using System.ServiceProcess;

public partial class SampleService : ServiceBase
{
    public SampleService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        this.WriteLog("OnStart");
        // Doing start service logic down here
        // Some service logic like create some files.
        // Or just leave it empty like a brand new Windows Service.
    }

    protected override void OnStop()
    {
        this.WriteLog("OnStop");
        // Doing clean service logic down here.
        // Some service logic like: delete files.  
        // Or just leave it empty like a brand new Windows Service.
    }

    static readonly object synObject = new object();

    public void WriteLog(string message)
    {
        if (string.IsNullOrEmpty(message))
        {
            return;
        }

        // Write log.
        lock (synObject)
        {
            using (var wr = new StreamWriter(@"C:\logfile.txt", true))
            {   
                wr.WriteLine(DateTime.Now + "-" + message);
            }
        }
    }
}

这是代码逻辑用于我的另一个应用程序内的启动和停止服务。我不能修改这个另一个应用程序。波纹管源代码模拟了发生的事情。

class Program
{
    static void Main(string[] args)
    {
        ServiceController sc = new ServiceController("SampleService");

         // start service
         sc.Start();

         // doing some logic cost deltaTime or just stand by in deltaTime.
         Thread.Sleep(deltaTime);
         try
         {
             // stop service first time, nothing happen.
             sc.Stop();
         }
         catch
         {
         }

         try
         {
             // stop service second times, by dump people or apllication.
             sc.Stop();
         }
         catch
         {
             // It got an exception here: "The service cannot accept control messages at this time".
             // But the service did stopped.
         }
    }
}

问题是:“当deltaTime太短时(低于3000ms,空OnStart(),OnStop()),Service将无法正常停止。输出日志OnStop将永远不会显示,这意味着OnStop方法没有调用。< / p>

我的服务将在OnStop上进行清理工作(比如删除一些文件),但如果没有调用,这些文件仍然存在。

我无法更改其他应用程序的逻辑,但我可以更改SampleService。

我想问:

  1. 这是一个Windows服务基础问题,我无法用它做任何事情吗?

  2. 无论如何,我可以在其他地方清理吗?

  3. 谢谢!

0 个答案:

没有答案