Let's assume you are using
System.Collections.Generic.Queue<T>
. Please see:
http://msdn.microsoft.com/en-us/library/7977ey2c.aspx[
^].
Read the section "Thread Safety". It explains what exactly you should do. You must implement your own synchronization. Practically, simply wrap the operations you need with
lock
, for example:
internal class QueueWrapper<T> {
internal void void Enqueue(T item) {
lock(SyncObject)
Implementation.Enqueue(item);
}
internal T Dequeue() {
lock(SyncObject)
return Implementation.Dequeue();
}
System.Collections.Generic.Queue<T> Implementation =
new System.Collections.Generic.Queue<T>();
object SyncObject = new Object();
}
Don't do
lock(this);
it would work but allow outside lock with the
QueueWrapper
instance. So, hiding the synchronization object
SyncObject
inside wrapper is a good fool-proof technique: no one will be able to create excessive synchronization with such object and compromise parallelism.
—SA