Calling ServiceBase.OnStart and OnStop… same instance?

点点圈 提交于 2019-12-20 05:24:31

问题


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 and OnStop respectively. Here's SSCE of the class:

partial class CometService : ServiceBase
{
    private Server<Bla> server;
    private ManualResetEvent mre;
    public CometService()
    {
        InitializeComponent();
    }       
    protected override void OnStart(string[] args)
    {
        //starting the server takes a while, but we need to complete quickly
        //here so let's spin off a thread so we can return pronto.
        new Thread(() =>
        {
            try
            {
                server = new Server<Bla>();
            }
            finally
            {
                mre.Set()
            }
        })
        {
            IsBackground = false
        }.Start();
    }

    protected override void OnStop()
    {
        //ensure start logic is completed before continuing
        mre.WaitOne();
        server.Stop();
    }
}

As can be seen, there's quite a lot of logic that requires that when we call OnStop, we're dealing with the same instance of ServiceBase as when we called OnStart.

Can I be sure that this is the case?


回答1:


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.




回答2:


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);
    ...
}


来源:https://stackoverflow.com/questions/10799937/calling-servicebase-onstart-and-onstop-same-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!