Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Queue.SyncRoot required for simple Enqueue/Dequeue across threads?

I have a WorkerThread that does a job on elements in the queue and several MiningThreads that create stuff need to be done by the WorkerThread.

To sum up: One thread Dequeues and several Enqueue.

Do I need to use the sync pattern proposed in msdn or I am thread safe in this specific scenario?

From msdn a simple sync-access pattern

Queue myCollection = new Queue();
lock(myCollection.SyncRoot)
{
    foreach (object item in myCollection)
    {
        // Insert your code here.
    }
}
like image 395
Odys Avatar asked Nov 30 '25 16:11

Odys


1 Answers

Yes, you need to sync.

There is a .NET4 queue where you would not need to sync, called "ConcurrentQueue": http://msdn.microsoft.com/en-us/library/dd267265.aspx

but you would have to migrate to .NET4, until then, you are stuck with doing sync yourself

Update: For your specific pattern, there is even a more specialised class available in .NET4, the BlockingCollection which embraces the Producer/Consumer pattern: http://msdn.microsoft.com/en-us/library/dd267312.aspx

still .NET4 tough... :)

like image 180
MichelZ Avatar answered Dec 02 '25 07:12

MichelZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!