启用队列< T>并发 [英] Enabling Queue<T> with concurrency

查看:131
本文介绍了启用队列< T>并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个previous <一href="http://stackoverflow.com/questions/4551087/how-to-work-threading-with-concurrentqueuet">question这是我提供我的解决方案;但是,我没有获得 ConcurrentQueue&LT; T&GT; ,因为我在NET 3.5的。我需要问答LT; T&GT; 允许并发。我读这问题,似乎present如果一个项目出现问题是的没有的队列和螺纹方法试图离队的项目。

I have a previous question which I have provided my solution; however, I don't have access to ConcurrentQueue<T> since I am on .Net 3.5. I need Queue<T> to allow concurrency. I read this question and seems to present a problem if an item is not in the queue and the threaded method tries to dequeue an item.

我现在的任务就是确定我是否可以得出自己的并发Queue类。这就是我想出了:

My task now is to determine whether I can derive my own concurrent Queue class. This is what I came up with:

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 (handler != null)
        {
            handler(this, table);
        }
    }
}

所以,当一个DataTable排队,EventArgs的将通过一个出列的表到事件订户。这是否会实现我提供一个线程安全的队列?

So, when a DataTable is queued, the EventArgs will pass a dequeued table to the event subscriber. Will this implementation provide me with a thread-safe Queue?

推荐答案

你出队的项目,如你入队他们。
您需要使用您的参数,以提高该事件。

You're dequeueing your items as you enqueue them.
You need to raise the event using your parameter.

无论它实际上是线程安全取决于你如何使用它。
如果你检查计数或检查的空虚,它不是线程安全的,不能轻易进行线程安全的。
如果不这样做,你也许可以用更简单的东西比一个队列。

Whether it's actually thread-safe depends on how you use it.
If you ever check the Count or check for emptiness, it's not threadsafe and cannot easily be made threadsafe.
If you don't, you can probably use something simpler than a queue.

这篇关于启用队列&LT; T&GT;并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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