I'm working on my first Windows Service project that involves some basic threading/parallelism. It's been pretty intense so far but I'm slowly beginning to understand threading (I guess we'll see about that...).
I have a Windows Service which will contain 2 loosely coupled worker threads. Thread A will be downloading files from a FTP server, unzipping/prepping them and saving to another directory where Thread B will have a FileSystemWatcher watching. Thread B will parse the files, do a number of things with the data, make some http calls, and finally archive and remove the files from the working directory.
I'm just beginning the work, and the problem I'm facing right now is how to wait for both thread A and thread B to return. I looked at this question: Thread.Join on multiple threads with timeout and had an idea.
The problem is if we're waiting on x threads to return with a x second timeout for each, with enough threads the service could appear non-responsive even under normal operation (I read the timeout before SCM complains is 30 seconds, right?). In addition, if we solve this problem by keeping track of time remaining to join as we loop over threads, the longer we wait on threads at the beginning of the collection of workers, the less time there is for remaining threads to return - so eventually with enough threads the service will appear non-responsive even though all the threads are returning within an expected period of time.
In this case I'll probably just thread.join both A and B on a 14 second timeout because I have only two workers and 14 seconds seems like enough time to return both.
If I had a variable number of worker threads (let's say > 8) would it be worth doing something like this? Would this work reliably?
Note: Don't use the following - it's a bad idea on multiple levels. See answers
protected override void OnStop()
{
// the service is stopping - set the event
Worker.ThreadStopEvent.Set();
// stop the threads
Parallel.ForEach(_workerThreads, t =>
{
t.Join(new TimeSpan(0, 0, 28));
});
}