下面是一些代码,有人想在生产应用程序中使用(不是我,诚实) - 我想请一些独立的反馈意见。线程代码反馈意见
public class JobProcessor<TJob> : IJobProcessor<TJob> where TJob : class
{
private readonly IJobQueue<TJob> theJobQueue =
new NullQueue<TJob>();
private Thread processorThread;
private bool shutdownRequested;
private readonly IJobObserver<TJob> theObserver = new NullObserver<TJob>();
public AutoResetEvent threadStartedEvent = new AutoResetEvent(false);
private int processorThreadId = 0;
private volatile TJob currentJob = null;
public JobProcessor(IJobQueue<TJob> jobQueue, IJobObserver<TJob> observer)
{
if (observer != null)
{
theObserver = observer;
}
shutdownRequested = false;
theJobQueue = jobQueue;
CreateAndRunThread();
}
private void CreateAndRunThread()
{
processorThread = new Thread(Run)
{
Name = "Tpk Processor Thread", IsBackground = true
};
processorThread.SetApartmentState(ApartmentState.STA);
processorThread.Priority = ThreadPriority.BelowNormal;
processorThread.Start();
}
public void Shutdown()
{
threadStartedEvent.WaitOne();
shutdownRequested = true;
theJobQueue.Interrupt(processorThreadId);
}
public TJob CurrentJob()
{
return currentJob;
}
private void Run()
{
processorThreadId = Thread.CurrentThread.ManagedThreadId;
threadStartedEvent.Set();
while (!BufferClearedAndShutDown())
{
try
{
ProcessNextMessage();
}
catch (ThreadAbortException)
{
CreateAndRunThread();
break;
}
catch (Exception e)
{ }
}
}
private void ProcessNextMessage()
{
currentJob = theJobQueue.RetrieveJob();
if (currentJob != null)
{
theObserver.ProcessMessage(this, currentJob);
}
currentJob = null;
}
private bool BufferClearedAndShutDown()
{
return theJobQueue.IsEmpty && shutdownRequested;
}
}
}
请删除不必要的代码注释;他们只会分散注意力,让阅读变得更难。 – 2009-02-14 19:51:15