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?
If you look in the
Program.csclass, you’ll see code like the following:That is, the instance is created by code within your own project. It’s that one instance that all Service Manager calls (including
OnStartandOnStop) are made against.