C# – Windows Service OnStop() not called

cservicewindows

I've written a program in C# that runs as a Windows Service. The application starts up and runs fine, but the OnStop function doesn't get called when I use the Management Console to stop the service.

The OnStart method starts a background thread for the main program, and that background thread starts another thread and a ThreadPool to do work for it.

OnStop I set a boolean flag that all the other threads check in order to see if they should stop processing. The threads should all then finish, and the program should end.

Here's the code for my OnStart

protected override void OnStart(string[] args)
    {
        base.OnStart(args);
        mainProgram.IsBackground = true;
        mainProgram.Start();
    }

That code works. Below is the code for OnStop, which as far as I can tell doesn't ever get called.

protected override void OnStop()
    {

        Log.LogMessage("Caught shutdown signal from the OS", "debug");
        base.OnStop();
        shutdown = true;
        mainProgram.Join(15000);
        if (mainProgram.IsAlive) mainProgram.Abort();
    }

That log message never gets written to the log file.

Any help would be appreciated. I don't even know where to start looking. Thanks.

EDIT
I solved the problem that was locking the background thread. I also commented out that logging statement, so I know the log statement isn't causing the problem.

I added a ManualResetEvent in addition to the boolean flag. The OnStop now looks like this:

protected override void OnStop()
    {
        System.Diagnostics.Debugger.Break();
        //Log.LogMessage("Caught shutdown signal from the OS", "debug");
        base.OnStop();
        shutdown = true;
        ShutdownX.Set();  //this is the ManualResetEvent
        mainProgram.Join(15000);
        if (mainProgram.IsAlive) mainProgram.Abort();
    }

The place this should stop the code is here in the mainProgram.RunAgent() function (which is its own thread)
while (!shutdown)
{

                SqlCommand DbCommand = dbConnection.CreateCommand();
                DbCommand.CommandText = "SELECT id, SourceID, CastingSN, Result FROM db_owner.queue";

                SqlDataReader DbReader = null;
                try
                {
                    DbReader = DbCommand.ExecuteReader();

                    while (DbReader.Read() && !shutdown)
                    {

                        long SourceID = DbReader.GetInt64(1);
                        string CastingSN = DbReader.GetString(2);
                        bool Result = DbReader.GetBoolean(3);

                        WaitCallback callback = new WaitCallback(oComm.RunAgent);
                        CommunicatorState commstate = new CommunicatorState(CastingSN, Result, SourceID);
                        ThreadPool.QueueUserWorkItem(callback, commstate);
                        callback = null;
                        commstate = null;

                    }
                    //Console.WriteLine("Finished Queueing Threads");
                }
                catch (SqlException Ex)
                {
                    Log.LogMessage("There was an error with a query run on the FlexNet Database.", "error");
                    Log.LogMessage(">> " + Ex.Message, "error");
                }
                finally
                {
                    if (DbReader != null) DbReader.Dispose();
                    DbCommand.Dispose();
                }
                ManualResetEvent[] handles = new ManualResetEvent[2] { eventX, ShutdownX };
                WaitHandle.WaitAny(handles);

                //eventX.WaitOne(Timeout.Infinite, true);
            }

I think this should read from the database, queue up all the threads it finds, then wait for either all the threads to finish processing (the eventX reset event) or the ShutdownX Event.

Once the ShutdownX event is triggered, the outer loop shouldn't continue because the shutdown bool is true, then the thread closes it's SQL connections and should terminate. None of this happens. Any ideas?

Best Answer

You are using ThreadPool. OnStop is reportedly never called until all tasks in the thread pool complete. See also here and here. However, I am leaning towards this not being the main or only cause as some people seem to be using it with success.

It seems to me that your question currently says that OnStop never gets called but that you have seen the log message that it emits. So I assume that OnStop does get called but that some of the threads do not notice that.

Please wrap all code that gets or sets shutdown in a lock statement, using a single global object. This is not for atomicity or mutual exclusion. This is to ensure proper memory barriers on a multiprocessor system.