在.NET上实现线程安全的阻塞队列

17
我正在寻找一个适用于.NET的线程安全阻塞队列的实现。 所谓“线程安全的阻塞队列”,是指: - 对队列进行线程安全访问,其中Dequeue方法调用会阻塞一个线程直到另一个线程放置(Enqueue)某个值。
目前我找到了这一个: http://www.eggheadcafe.com/articles/20060414.asp (但它是针对.NET 1.1的)。
能否有人评论/批评这个实现的正确性。 或提出其他建议。 提前致谢。
7个回答

22

你能提供一个代码示例,添加一些方法,以便我们可以看到其运行情况吗? - theJerm

9
这个怎么样?在.NET中创建阻塞队列
如果你需要用于.NET 1.1(我不确定问题是关于哪个版本的),只需删除泛型并将T替换为object即可。

谢谢提供链接。奇怪的是我搜索“队列”时没有找到那个主题。好的,那个主题和我的主题是关于同一件事情。 顺便说一下:我不需要将其移植到 .net 1.1 版本。 相关主题中的解决方案与 http://www.eggheadcafe.com/articles/20060414.asp 上的解决方案非常相似。 - Shrike
1
@Shrike,一点也不奇怪。这只是StackOverflow搜索有多糟糕的又一个例子。它太糟糕了,以至于每个人都会告诉你最好使用Google(和“site:”命令)来代替。 - Ash
@Ash:那可能是真的...这绝对是我在 Stack Overflow 上搜索的方式;-p - Marc Gravell

1

1

微软的例子很好,但它没有封装成一个类。此外,它要求使用者线程在MTA中运行(因为涉及到WaitAny调用)。在某些情况下,你可能需要在STA中运行(例如,如果你在进行COM互操作)。在这些情况下,无法使用WaitAny。

我有一个简单的阻塞队列类,可以解决这个问题,你可以在这里找到: http://element533.blogspot.com/2010/01/stoppable-blocking-queue-for-net.html


1

1
我认为这只是一个线程安全队列,与他所询问的略有不同。 - tylerl
1
是的,我发布后看到了那个。已编辑以反映。 - Chad Grant
Queue.Synchronized()返回的包装器的Dequeue方法是否会阻塞当前线程?不会。 假设您有两个线程,其中一个将值放入队列中,另一个从该队列中获取。第二个线程必须在循环中轮询队列以消耗CPU。这是不好的。 - Shrike

0

微软有一个很好的关于这个的示例:

//Copyright (C) Microsoft Corporation.  All rights reserved.

using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;

// The thread synchronization events are encapsulated in this 
// class to allow them to easily be passed to the Consumer and 
// Producer classes. 
public class SyncEvents
{
    public SyncEvents()
    {
        // AutoResetEvent is used for the "new item" event because
        // we want this event to reset automatically each time the
        // consumer thread responds to this event.
        _newItemEvent = new AutoResetEvent(false);

        // ManualResetEvent is used for the "exit" event because
        // we want multiple threads to respond when this event is
        // signaled. If we used AutoResetEvent instead, the event
        // object would revert to a non-signaled state with after 
        // a single thread responded, and the other thread would 
        // fail to terminate.
        _exitThreadEvent = new ManualResetEvent(false);

        // The two events are placed in a WaitHandle array as well so
        // that the consumer thread can block on both events using
        // the WaitAny method.
        _eventArray = new WaitHandle[2];
        _eventArray[0] = _newItemEvent;
        _eventArray[1] = _exitThreadEvent;
    }

    // Public properties allow safe access to the events.
    public EventWaitHandle ExitThreadEvent
    {
        get { return _exitThreadEvent; }
    }
    public EventWaitHandle NewItemEvent
    {
        get { return _newItemEvent; }
    }
    public WaitHandle[] EventArray
    {
        get { return _eventArray; }
    }

    private EventWaitHandle _newItemEvent;
    private EventWaitHandle _exitThreadEvent;
    private WaitHandle[] _eventArray;
}

// The Producer class asynchronously (using a worker thread)
// adds items to the queue until there are 20 items.
public class Producer 
{
    public Producer(Queue<int> q, SyncEvents e)
    {
        _queue = q;
        _syncEvents = e;
    }
    public void ThreadRun()
    {
        int count = 0;
        Random r = new Random();
        while (!_syncEvents.ExitThreadEvent.WaitOne(0, false))
        {
            lock (((ICollection)_queue).SyncRoot)
            {
                while (_queue.Count < 20)
                {
                    _queue.Enqueue(r.Next(0, 100));
                    _syncEvents.NewItemEvent.Set();
                    count++;
                }
            }
        }
        Console.WriteLine("Producer thread: produced {0} items", count);
    }
    private Queue<int> _queue;
    private SyncEvents _syncEvents;
}

// The Consumer class uses its own worker thread to consume items
// in the queue. The Producer class notifies the Consumer class
// of new items with the NewItemEvent.
public class Consumer
{
    public Consumer(Queue<int> q, SyncEvents e)
    {
        _queue = q;
        _syncEvents = e;
    }
    public void ThreadRun()
    {
        int count = 0;
        while (WaitHandle.WaitAny(_syncEvents.EventArray) != 1)
        {
            lock (((ICollection)_queue).SyncRoot)
            {
                int item = _queue.Dequeue();
            }
            count++;
        }
        Console.WriteLine("Consumer Thread: consumed {0} items", count);
    }
    private Queue<int> _queue;
    private SyncEvents _syncEvents;
}

public class ThreadSyncSample
{
    private static void ShowQueueContents(Queue<int> q)
    {
        // Enumerating a collection is inherently not thread-safe,
        // so it is imperative that the collection be locked throughout
        // the enumeration to prevent the consumer and producer threads
        // from modifying the contents. (This method is called by the
        // primary thread only.)
        lock (((ICollection)q).SyncRoot)
        {
            foreach (int i in q)
            {
                Console.Write("{0} ", i);
            }
        }
        Console.WriteLine();
    }

    static void Main()
    {
        // Configure struct containing event information required
        // for thread synchronization. 
        SyncEvents syncEvents = new SyncEvents();

        // Generic Queue collection is used to store items to be 
        // produced and consumed. In this case 'int' is used.
        Queue<int> queue = new Queue<int>();

        // Create objects, one to produce items, and one to 
        // consume. The queue and the thread synchronization
        // events are passed to both objects.
        Console.WriteLine("Configuring worker threads...");
        Producer producer = new Producer(queue, syncEvents);
        Consumer consumer = new Consumer(queue, syncEvents);

        // Create the thread objects for producer and consumer
        // objects. This step does not create or launch the
        // actual threads.
        Thread producerThread = new Thread(producer.ThreadRun);
        Thread consumerThread = new Thread(consumer.ThreadRun);

        // Create and launch both threads.     
        Console.WriteLine("Launching producer and consumer threads...");        
        producerThread.Start();
        consumerThread.Start();

        // Let producer and consumer threads run for 10 seconds.
        // Use the primary thread (the thread executing this method)
        // to display the queue contents every 2.5 seconds.
        for (int i = 0; i < 4; i++)
        {
            Thread.Sleep(2500);
            ShowQueueContents(queue);
        }

        // Signal both consumer and producer thread to terminate.
        // Both threads will respond because ExitThreadEvent is a 
        // manual-reset event--so it stays 'set' unless explicitly reset.
        Console.WriteLine("Signaling threads to terminate...");
        syncEvents.ExitThreadEvent.Set();

        // Use Join to block primary thread, first until the producer thread
        // terminates, then until the consumer thread terminates.
        Console.WriteLine("main thread waiting for threads to finish...");
        producerThread.Join();
        consumerThread.Join();
    }
}

0
请记住,如果您完全控制调用代码,则在其中进行锁定可能是更好的选择。考虑在循环中访问您的队列:您将不必多次获取锁定,可以避免潜在的性能损失。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接