Enabling Queuelt;Tgt; with concurrency(启用队列lt;Tgt;并发)
问题描述
我之前有一个问题,我已经提供了我的解决方案;但是,由于我使用的是 .Net 3.5,因此我无法访问 ConcurrentQueue<T>
.我需要 Queue<T>
来允许并发.我读了这个 问题,如果一个项目是 不在队列中,并且线程方法尝试使项目出队.
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.
我现在的任务是确定我是否可以派生我自己的并发队列类.这是我想出的:
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.
它是否真的是线程安全的取决于你如何使用它.
如果您曾经检查过 Count
或检查是否为空,则它不是线程安全的,也不能轻易地成为线程安全的.
如果你不这样做,你可能可以使用比队列更简单的东西.
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.
这篇关于启用队列<T>并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:启用队列<T>并发


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01