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
{
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)
{
}
Here is the StartThreadPool method:
[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)
{
}
}
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;
serviceStarted = false;
workerThread.Join(TimeSpan.FromSeconds(30));
}
ProcessRequestList, foreach, StopService. true, .
:
50 . 50 , , .
50 , , , , .
, OnStop .
, ?