在C#中的队列和等待句柄 [英] Queues And Wait Handles in C#

查看:556
本文介绍了在C#中的队列和等待句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code。在我的应用程序了好几年,从来没有从中看出一个问题。

I've had the following code in my application for some years and have never seen an issue from it.

while ((PendingOrders.Count > 0) || (WaitHandle.WaitAny(CommandEventArr) != 1))
{
    lock (PendingOrders)
    {
       if (PendingOrders.Count > 0)
       {
           fbo = PendingOrders.Dequeue();
       }
       else
       {
           fbo = null;
       }
    }

    // Do Some Work if fbo is != null
}

在哪里CommandEventArr由该NewOrderEvent(自动重置事件)和ExitEvent(手动复位事件)的。

Where CommandEventArr is made up of the NewOrderEvent (an auto reset event) and the ExitEvent (a manual reset event).

但我不知道这是否是线程安全的(enqueing和运行上面的code一个消费者线程之前,所有的锁队列假定ñ生产者线程)。此外,我们可以假设Queue.Count属性只是返回从队列类的一个实例的Int32值(无挥发性或交错或锁等)。

But I'm not sure if this is thread safe (assuming N producer threads that all lock the queue before enqueing and one consumer thread that runs the code above). Also, we can assume that the Queue.Count property just returns one instance Int32 value from the Queue class (without volatile or interlocked or a lock, etc.).

做什么用队列和的AutoResetEvent用通常的模式来解决这个问题,做我想要做的code以上?

What's the usual pattern used with a Queue and an AutoResetEvent to fix this and do what I'm trying to do with the code above?

(编辑更改的问题后小幅有人正确地指出,Queue.Count可以做任何事情,它的具体实施)。

(Edited to change the question slightly after it was correctly pointed out that Queue.Count could do anything and its implementation specific).

推荐答案

看起来相当线程安全对我,对了WaitAny()会简单地立即完成,因为你的事件已经设置。这是的没有的一个问题。

Looks quite thread-safe to me, the WaitAny() will simply complete immediately because thee event is already set. That's not a problem.

不要打破线程同步的作品。但是,如果你想有一个更好的捕鼠器,那么你可以考虑乔·达菲的的BlockingQueue在此杂志文章。它的一个更普遍的版本可以在.NET 4.0中, System.Collections.Concurrent。 BlockingCollection ,并ConcurrentQueue作为它的实际执行。

Don't break threading sync that works. But if you want a better mousetrap then you could consider Joe Duffy's BlockingQueue in this magazine article. A more general version of it is available in .NET 4.0, System.Collections.Concurrent.BlockingCollection with ConcurrentQueue as a practical implementation of it.

这篇关于在C#中的队列和等待句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆