I have a queue of tasks that are processed by a number of different threads. I want the threads that are doing the task processing to process until the task queue is empty or until a certain amount of time (say 5000 milliseconds) have passed.
I'm wondering what's a reliable way to determine the amount of time that has passed across threads in c#?
Ideally I'd use something like StopWatch
but it seems like that might not be threadsafe...
Is there some better alternative thing that I can use to calculate time elapsed from a single point from multiple different threads?
I want to write code that looks something like this:
Stopwatch stopwatch = new Stopwatch();
CountdownEvent runningProcessors = new CountdownEvent(0);
// Main thread starts processing on threadpool threads, and itself
void SpawnProcessors() {
runningProcessors(1);
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < chosenNumberOfThreads; i++)
{
// process on threads
pendingJobs.AddCount();
ThreadPool.QueueUserWorkItem(_ => ProcessQueue());
}
// also process on the main thread
ProcessQueue();
// wait for all processing to finish
pendingJobs.Wait();
stopwatch.Stop();
}
// Method run by processing threads
void ProcessQueue() {
while (workQueue.Count > 0 && stopwatch.ElapsedMilliseconds < 5000) {
workQueue.Dequeue().DoWork();
}
pendingJobs.Signal();
}