.NET Framework 4.5.2. I'm trying to update some old code and trying to figure out how to manage the number of running threads for a specific ID. This is the code.
foreach (ThreadGroup thread_group in threadGroups)
{
if (ImportQueues.TryGetValue(thread_group.ThreadGroupID, out BlockingCollection<ImportFrequency> configuration))
{
if (configuration.Count > thread_group.ThreadCount)
{
// increase number of threads running for this group
}
else if (configuration.Count < thread_group.ThreadCount)
{
// decrease number of threads running for this group
}
}
else // Spin up the initial threads
{
ImportQueues.Add(thread_group.ThreadGroupID, new BlockingCollection<ImportFrequency>());
for (int x = 0; x < thread_group.ThreadCount; x++)
{
Thread import_thread = new Thread(new ParameterizedThreadStart(ProcessImportQueue)) { IsBackground = true };
import_thread.Start((ImportQueues[thread_group.ThreadGroupID]));
}
}
}
Essentially, we're running thread_group.ThreadCount
number of threads for each group's blocking collection, which will be continually updated. Additionally, thread_group
can be updated to change the ThreadCount
. If the change increases the number of threads, spin up more to process the blocking collection. If it decreases, wait for the difference in number of threads to finish while the others continue running.
Is this possible with this paradigm or do I need to find a better way to manage threads?
Edit: One solution I tried with this is using CancellationTokens. When I start up a thread, I pass in a model that contains the context as well as a CancellationToken. That model is saved to a global variable. If we need to decrease the number of threads, I go through however many need to be stopped and cancel the token, which stops the infinite loop for that one thread and stops it.