很抱歉这个问题不是很清楚,如果我知道用正确的词语来描述问题,谷歌可能会想出答案。
我正在寻找一个队列类:
就像在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并仍然存在死锁。
答案 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