Stopping the Windows Multithreaded Service

I have a multi-threaded Windows service in .Net 3.5, and I am having certain problems to stop the service properly when more than one thread is created.

This service is used to create only one thread to do all the work, and I just changed it to multithreading. It works fine, but when the service is stopped, if multiple threads are running, it will hang until all threads are complete.

When the service is running, I create a background thread to handle the main process:

    protected override void OnStart(string[] args)
    {
        try
        {
            //Global variable that is checked by threads to learn if service was stopped
            DeliveryConstant.StopService = false;
            bool SetMaxThreadsResult = ThreadPool.SetMaxThreads(10, 10);

            ThreadStart st = new ThreadStart(StartThreadPool);
            workerThread = new Thread(st);
            workerThread.IsBackground = true;
            serviceStarted = true;
            workerThread.Start();
        }
        catch (Exception ex)
        {
            //Log something;
        }

Here is the StartThreadPool method:

    //Tried with and without this attribute with no success...
    [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
    public void StartThreadPool()
    {
        while (serviceStarted)
        {
            ProcessInfo input = new ProcessInfo();

            try
            {
                int? NumPendingRequests = GetItems(50, (Guid?)input.ProcessID);

                if (NumPendingRequests > 0)
                {
                    input.ProcessType = 1;
                    input.ProcessID = Guid.NewGuid();
                    ThreadPool.QueueUserWorkItem(new WaitCallback(new DispatchManager().ProcessRequestList), input);
                 }
            }
            catch (Exception ex)
            {
                //Some Logging here
            }
        }

        DeliveryConstant.StopService = true;
    }

I created a static variable in a separate class to notify threads that were stopped by the service. When the value for this variable is true, all threads should stop the main loop (a for each loop):

        public static bool StopService;

, OnStop:

protected override void OnStop()
    {
        DeliveryConstant.StopService = true;

        //flag to tell the worker process to stop
        serviceStarted = false;

        workerThread.Join(TimeSpan.FromSeconds(30));
    }

ProcessRequestList, foreach, StopService. true, .

: 50 . 50 , , . 50 , , , , .

, OnStop .

, ?

+5
2

, OnStop , ThreadPool , , .

Windows, , ThreadPool, . DoWork() . , , .

+9

StopService, , . . :

object @lock;

...

lock (@lock)
{
    StopService = true;
}

. , , , .

volatile , , .

+3

All Articles