spender
spender

Reputation: 120498

Calling ServiceBase.OnStart and OnStop... same instance?

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?

Upvotes: 1

Views: 6804

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239754

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.

Upvotes: 2

munissor
munissor

Reputation: 3785

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

Upvotes: 1

Related Questions