Here is example how syncronized queue is implemented. Basically it is a
*very simple wrapper:
internal class SyncQ : Queue
{
private Queue q;
private object syncRoot;
public SyncQ(Queue q)
{
this.q = q;
this.syncRoot = this.q.SyncRoot;
}
public override void Clear()
{
lock(this.syncRoot)
{
this.q.Clear();
}
}
public override object Dequeue()
{
object obj;
lock(syncRoot)
{
obj = this.q.Dequeue();
}
return obj;
}
//And so on...
}
Naturally, you can do this yourself if you need special function. The .Net
sync wrapper should work on any queue that derives from Queue. However, I
agree with Jon and would manually sync myself as you will probably need to
anyway at different points as your complexity grows. Say you want to check
the Count and then Dequeue only if count is > 0. You need to lock SyncRoot
anyway even if using a Sync Wrapper as you want the count test and the
Dequeue operation to be one atomic operation. So in this case, you end up
with three Monitor locks, the manual SyncRoot you do yourself, and the two
locks the SyncWrapper does (one for Count "Get" and one for the Dequeue
method). It is the same Monitor object, but a lock is taken and released
three times. There are others you will run into and others that could
result in even more locks being taken and released. This is one example of
how simple .Net can be, but yet can hurt our perf if we don't consider what
is really happening under the covers. Just some thoughts. Cheers!
--
William Stacey, MVP
http://mvp.support.microsoft.com
"rmunson8" <rm******@discussions.microsoft.com> wrote in message
news:D7**********************************@microsof t.com...
I have a derived class from the Queue base class. I need it to be
thread-safe, so I am using the Synchronized method (among other things out
of scope of this issue). The code below compiles, but at runtime, the cast
of "Queue.Synchronized(new EventQueue())" to an EventQueue object is failing
stating invalid cast.
Why?
public class EventQueue : System.Collections.Queue { ... }
public class AnotherClass {
private static EventQueue q = null;
public void AnotherMethod() {
q = (EventQueue)Queue.Synchronized(new EventQueue());
}
}