Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop a windows service application from a thread?

I have a windows service that starts a thread in the OnStart method.

Basically I want to be able to stop the service if something goes really wrong (like an unhandled exception).

Currently I'm using ServiceBase.Stop() but that involves having a ServiceBase instance somewhere visible to the thread, which in turn involves having my instance be declared as public static in the main program.

Is there any "better way" to stop the service? If it isn't ... is it safe to do it that way?

like image 224
Jorge Córdoba Avatar asked Feb 25 '09 17:02

Jorge Córdoba


1 Answers

The easiest and, in my opinion, cleanest way is to use a public static property of the service class. The only time this won't work is if you are using the same service class to run multiple services in the same process, something that is very rare.

private static MyService m_ServiceInstance;

public static MyService ServiceInstance
{
    get { return m_ServiceInstance; }
}

public MyService()
{
    InitializeComponents();
    //Other initialization
    m_ServiceInstance = this;
}

Injecting the service instance into every method that could possibly need it is an alternative but it can quickly get messy and it has no real advantages over just using a static property.

like image 146
Stephen Martin Avatar answered Oct 13 '22 01:10

Stephen Martin