在我的C#/NET 3.5应用程序中,我有一个任务队列(线程安全),我有5个工作线程必须不断地查找队列中的任务。如果有任务可用,任何一个工作线程都会出列任务并采取所需行动。
我的工作线程类如下:
我的工作线程类如下:
public class WorkerThread
{
//ConcurrentQueue is my implementation of thread safe queue
//Essentially just a wrapper around Queue<T> with synchronization locks
readonly ConcurrentQueue<CheckPrimeTask> mQ;
readonly Thread mWorker;
bool mStop;
public WorkerThread (ConcurrentQueue<CheckPrimeTask> aQ) {
mQ = aQ;
mWorker = new Thread (Work) {IsBackground = true};
mStop = false;
}
private void Work () {
while (!mStop) {
if (mQ.Count == 0) {
Thread.Sleep (0);
continue;
}
var task = mQ.Dequeue ();
//Someone else might have been lucky in stealing
//the task by the time we dequeued it!!
if (task == null)
continue;
task.IsPrime = IsPrime (task.Number);
task.ExecutedBy = Thread.CurrentThread.ManagedThreadId;
//Ask the threadpool to execute the task callback to
//notify completion
ThreadPool.QueueUserWorkItem (task.CallBack, task);
}
}
private bool IsPrime (int number) {
int limit = Convert.ToInt32 (Math.Sqrt (number));
for (int i = 2; i <= limit; i++) {
if (number % i == 0)
return false;
}
return true;
}
public void Start () {
mStop = false;
mWorker.Start ();
}
public void Stop () {
mStop = true;
}
}
问题是当队列为空时,它会消耗太多的CPU(近98%)。我尝试使用AutoResetEvent来通知工作线程队列已经改变。因此,它们有效地等待该信号来设置。这将CPU降至接近0%,但我并不完全确定这是否是最佳方法。您能否建议一种更好的方法,使线程保持空闲而不会影响CPU使用率?