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);
}
}
}
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?
que
is utterly useless. You should lock on areadonly object key = new object();
. – FormalizeICollection que
andlock(que.SyncRoot)
based on MSDN: msdn.microsoft.com/en-us/library/bb344892.aspx – DanelledaneteSyncRoot
is useful if you have disjoint pieces of code that need to lock for the same collection. In your case,que
isnull
. You just need to lock on a single object in your methods. – Formalize