我的基本问题是,如果队列为空,则需要立即处理队列中的项目,或者如果已处理项目,则将项目添加到队列中并离开。
我正在尝试一种使用 peek 来简化事情的技术,并且想知道可能会遇到什么问题。谢谢!
void SequenceAction(Action action) {
bool go = false;
lock (_RaiseEventQueueLock) {
_RaiseEventQueue.Enqueue(action);
go = (_RaiseEventQueue.Count == 1);
}
// 'go' can only be true if queue was empty when queue
// was locked and item was enqueued.
while (go) {
#if naive_threadsafe_presumption
// Peek is threadsafe because in effect this loop owns
// the zeroeth item in the queue for as long as the queue
// remains non-empty.
(_RaiseEventQueue.Peek())();
#else
Action a;
lock (_RaiseEventQueueLock) {
a = _RaiseEventQueue.Peek();
}
a();
#endif
// Lock the queue to see if any item was enqueued while
// the zeroeth item was being processed.
// Note that the code processing an item can call this
// function reentrantly, adding to its own todo list
// while insuring that that each item is processed
// to completion.
lock (_RaiseEventQueueLock) {
_RaiseEventQueue.Dequeue();
go = (_RaiseEventQueue.Count > 0);
}
}
}