System.Collection.Generic.Queue - Where did SyncRoot go?

G

Guest

I'm not sure if I've just lost it but, I no longer see the property SyncRoot
on a Queue. I see that it's a member of the ICollection Base Object, but it's
not exposed.

Was this intended? Besides writing a wrapper class for Queue, what is the
intended way to lock the queue to enforce proper synchronization?

using System;
using System.Collections.Generic;
using System.Text;

namespace DummyApp
{
class DummyApp
{
static void Main(string[] args)
{
Queue<int> iq = new Queue<int>();

lock(q.SyncRoot)
{
DoSomething();
}
}
}
}

This is the error I would get when compiling

'System.Collections.Generic.Queue<int>' does not contain a definition for
'SyncRoot'
 
M

Marc Gravell

I believe the view taken was that in most cases the SyncRoot approach
simply wasn't worth it; and synchronising *inside* the object (for
most collections) is worse, as it only protects individual objects -
not longer atomic operations. Note that if you cast to ICollection,
the SyncRoot is still there, and looking at reflector it will allocate
a new sync object when first requested (even though it reports
IsSynchronized as false).

However; you only need to worry about the SyncRoot if you are
threading... and if you are threading you have enough complexity
already... I would tend to encapsulate the Queue<T> into a class that
describes what I am trying to do, rather than how I am implementing
it; since I recognise that this class is threaded, I can make it
thread-safe with a private lock inside the object, as well as
encapsulating other features such as Monitor.Wait (if reading empty)
and Monitor.Pulse (if writing first entry) - assuming of course that
this is a work queue (which it sounds like).

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top