Calling ServiceBase.OnStart and OnStop… same instance?

后端 未结 2 586
感情败类
感情败类 2021-01-25 17:04

So I\'ve got a Windows service written in c#. The service class derives from ServiceBase, and starting and stopping the service calls instance methods OnStart

相关标签:
2条回答
  • 2021-01-25 17:39

    If you look in the Program.cs class, you'll see code like the following:

    private static void Main()
    {
        ServiceBase.Run(new ServiceBase[]
                    {
                        new CometService()
                    });
    }
    

    That is, the instance is created by code within your own project. It's that one instance that all Service Manager calls (including OnStart and OnStop) are made against.

    0 讨论(0)
  • I guess is the same instance. You can do a quick test adding a static field in the class to keep track of the reference to the object used in the OnStart and comparing it to the instance of the OnStop.

    private static CometService instance = null;
    
    protected override void OnStart(...)
    {
        instance = this;
        ...
    }
    
    protected override void OnStop()
    {
        object.ReferenceEquals(this, instance);
        ...
    }
    
    0 讨论(0)
提交回复
热议问题