Windows Service Threading Continued

StuartProgramming Blog

So appropriate threading in a Windows service continued to give me issues after the last discovery of the multi-threaded timer. This time, I discovered a few additional relevant items about starting and stopping a windows service.

The first problem I identified in my service is that the OnStart function MUST EXIT or the service will stay in “Starting” status and never enter “Started”. This means that your service needs to launch a thread inside the OnStart function instead of launching right into your program loop. This was easy enough to solve.

Then when the stop command on the windows services manager is executed, this service must be allowed to complete an execution cycle BEFORE halting the service. I think the following solution neatly solves both of these. Let me know what you think.

Thread mainThread;
object mainLoopLockObject;

protected override void OnStart(string[] args) {
	terminateRequested = false;
	ThreadStart threadDelegate = new ThreadStart(debugStart);
	mainThread = new Thread(threadDelegate);
	mainThread.Start();
	//debugStart();
}

public void debugStart() {
	//initialize the lock object
	mainLoopLockObject = new object();
	loadConfigFileVariables();
	lock (mainLoopLockObject) {
		while ((!terminateRequested)) {
			processloop();
			if (terminateRequested) {
				break;
			}
			Thread.Sleep(timercycleinseconds * 1000);
		}
	}
}

protected override void OnStop() {
	terminateRequested = true;
	//request that the OS allow at 10 minutes considering this service non-responsive
	RequestAdditionalTime(10 * 60 * 1000);
	lock (mainLoopLockObject) {
		sharedOperations.writeDebug("Service Halt Completed", debuglevel.error);
	}
	//exit without error
	ExitCode = 0;
}

Tags: 

StuartWindows Service Threading Continued