如何将工作项分派给单个线程

时间:2010-02-23 16:36:06

标签: .net multithreading

很抱歉这个问题不是很清楚,如果我知道用正确的词语来描述问题,谷歌可能会想出答案。

我正在寻找一个队列类:

  • 允许任意数量的线程将项目放入队列
  • 项目按照添加到队列的顺序进行处理
  • 我不介意什么线程处理项目
  • 一次只处理一个项目。
  • 如果队列中没有项目,我宁愿没有线程阻塞等待项目添加到队列中。
  • 正常情况是大部分时间队列都是空的。

就像在WinForms窗口上使用BeginInvoke所发生的那样...(或者如果你已经完成了原始的win32编程,则为PostMessage) 我们正在使用.net 3.5

我正在寻找.net框架中现成的东西,或者是一个具有良好单元测试的开源项目,因为我不希望为家庭制作解决方案编写所有单元测试。< / p>


有关背景信息,请参阅Why are my message be processed out of order over a single WCF TCP channel (with ConcurrencyMode.Reentrant)?使用此depatcher,我可以更改为使用ConcurrencyMode.Single并仍然存在死锁。

3 个答案:

答案 0 :(得分:4)

这是一个可以做到这一点的课程草图:

public class WorkerQueue<T> {
    private Queue<T> workerQueue   = new Queue<T>();
    private object   padlock       = new object();
    private bool     isProcessing  = false;
    private Thread   workerThread;

    public void QueueWorkItem(T item) {
        lock(padlock) {
            workerQueue.Enqueue(item);
            if (!isProcessing) {
                isProcessing = true;
                workerThread = new Thread(() => { this.ProcessWork });
                workerThread.Start();

            }
        }
    }

    private void ProcessWork() {
        // 1) Thread-safe dequeue operation
        // 2) Keep processing while work is on the queue. External callers can
        //    add items to the queue while this is ongoing.
        // 3) When the queue is empty, set isProcessing to false (thread-safely)
    }

}

应用程序会像这样使用它:

public class Application {
    private WorkerQueue<object> workerQueue = new WorkerQueue<object>();

    // This can run on multiple threads if need be
    public void SomeMethodThatCreatesWork() {
        object workItem = ExternalCall();
        this.workerQueue.QueueWorkItem(workItem);
    }
}

让应用程序停止处理可能也很有用,可能是通过添加ProcessWork在每个项目出列后可以检查的标志,但是不清楚如何处理未处理的项目(也许它会足以允许访问它们并让调用者决定。)

答案 1 :(得分:1)

使用CCR提供的端口原语是高效的FIFO队列,Dispatcher,DispatcherQueues和Arbiter原语允许您控制任务调度。

答案 2 :(得分:0)

使用ThreadPool,但使用SetMaxThreads将运行线程数限制为一个。使用QueueUserWorkItem将更多任务添加到队列中。 http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx