相关疑难解决方法(0)

在.NET中创建阻塞队列<T>?

我有一个场景,我有多个线程添加到队列和多个线程从同一队列读取.如果队列达到特定大小,则填充队列的所有线程将在添加时被阻止,直到从队列中删除项目为止.

下面的解决方案就是我现在正在使用的问题,我的问题是:如何改进?是否有一个对象已经在我应该使用的BCL中启用此行为?

internal class BlockingCollection<T> : CollectionBase, IEnumerable
{
    //todo: might be worth changing this into a proper QUEUE

    private AutoResetEvent _FullEvent = new AutoResetEvent(false);

    internal T this[int i]
    {
        get { return (T) List[i]; }
    }

    private int _MaxSize;
    internal int MaxSize
    {
        get { return _MaxSize; }
        set
        {
            _MaxSize = value;
            checkSize();
        }
    }

    internal BlockingCollection(int maxSize)
    {
        MaxSize = maxSize;
    }

    internal void Add(T item)
    {
        Trace.WriteLine(string.Format("BlockingCollection add waiting: {0}", Thread.CurrentThread.ManagedThreadId));

        _FullEvent.WaitOne();

        List.Add(item);

        Trace.WriteLine(string.Format("BlockingCollection …
Run Code Online (Sandbox Code Playgroud)

.net c# queue collections multithreading

161
推荐指数
6
解决办法
10万
查看次数

使用并发启用队列<T>

我有一个先前的问题,我提供了我的解决方案; 但是,ConcurrentQueue<T>因为我在.Net 3.5上,所以我没有访问权限.我需要Queue<T>允许并发.我读了这个问题,如果一个项目不在队列中并且线程方法试图使项目出列,则似乎存在问题.

我现在的任务是确定是否可以派生自己的并发队列类.这就是我想出的:

public sealed class ConcurrentQueue : Queue<DataTable>
{
    public event EventHandler<TableQueuedEventArgs> TableQueued;
    private ICollection que;

    new public void Enqueue(DataTable Table)
    {
        lock (que.SyncRoot)
        {
            base.Enqueue(Table);
        }

        OnTableQueued(new TableQueuedEventArgs(Dequeue()));
    }

    //  this is where I think I will have a problem...
    new public DataTable Dequeue()
    {
        DataTable table;

        lock (que.SyncRoot)
        {
            table = base.Dequeue();
        }

        return table;
    }

    public void OnTableQueued(TableQueuedEventArgs table)
    {
        EventHandler<TableQueuedEventArgs> handler = TableQueued;

        if …
Run Code Online (Sandbox Code Playgroud)

c# queue multithreading .net-3.5

10
推荐指数
1
解决办法
5780
查看次数

标签 统计

c# ×2

multithreading ×2

queue ×2

.net ×1

.net-3.5 ×1

collections ×1