My aim is to avoid using threadpool threads for CPU bound work, thus avoiding a situation where IIS stops responding to new requests.
Can you see any problems with the code below? Is this a safe/clean approach? Can you offer any improvements?
private static ConcurrentQueue<Job> Jobs = new ConcurrentQueue<Job>();
static int threadCount = 0;
private void QueueJob(Job job)
{
bool startQueue=false;
lock(Jobs)
{
if (threadCount == 0)
{
Interlocked.Increment(ref threadCount);
startQueue = true;
}
}
Jobs.Enqueue(job);
if (startQueue)
{
var t= new Thread(new ThreadStart(ConsumeQueue));
t.Start();
}
}
private void ConsumeQueue()
{
while (true)
{
lock (Jobs)
{
if (!Jobs.Any())
{
Interlocked.Decrement(ref threadCount);
return;
}
}
Job j;
var jobToDo = Jobs.TryDequeue(out j);
if (jobToDo)
{
DoCPUBoundWork(j);
}
}
}
ConcurrentQueue<T>
is already thread-safe, I don't think you need to do any locking to access it. \$\endgroup\$ResizeJobs
? I don't think I could say whether or not any of the locks needed without knowing whatResizeJobs
is. \$\endgroup\$ResizeJobs
should beJobs
! \$\endgroup\$