The OnStart()
method is called by the system when the service is started. The method should return as quickly as possible since the system will be waiting for a successful return to indicate that the service is running. Inside this method, you'll typically launch the code that will perform the service's task. This may include starting a thread, starting a timer, open a WCF service host, performing an asynchronous socket command, etc.
Here's a simple example that launches a thread that simply executes an loop that waits for the service to be stopped.
private ManualResetEvent _shutdownEvent;
private Thread _thread;
protected override void OnStart(string[] args)
{
// Uncomment this line to debug the service.
//System.Diagnostics.Debugger.Launch();
// Create the event used to end the thread loop.
_shutdownEvent = new ManualResetEvent(false);
// Create and start the thread.
_thread = new Thread(ThreadFunc);
_thread.Start();
}
protected override void OnStop()
{
// Signal the thread to stop.
_shutdownEvent.Set();
// Wait for the thread to end.
_thread.Join();
}
private void ThreadFunc()
{
// Loop until the service is stopped.
while (!_shutdownEvent.WaitOne(0))
{
// Put your service's execution logic here. For now,
// sleep for one second.
Thread.Sleep(1000);
}
}
If you've gotten to the point of installing the service, it sounds like you're well on your way. For what it's worth, I've got step-by-step instructions for creating a service from scratch here and follow-on instructions for having the service install/uninstall itself from the command line without relying on InstallUtil.exe
here.