Would it be thread-safe if I solely call Enqueue(T) from multiple threads simultaneously and wait for those threads to complete before calling Dequeue() or enumerating the queue?
var queue = new Queue<int>();
Action enqueue = () =>
{
for (int i = 0; i < 100000; i++)
queue.Enqueue(i);
};
var tasks = new[]
{
new Task(enqueue),
new Task(enqueue),
new Task(enqueue)
};
foreach (var task in tasks)
task.Start();
Task.Factory.ContinueWhenAll(tasks, t =>
{
while (queue.Count > 0)
Console.WriteLine(queue.Dequeue());
});
The documentation also states that instance members of this type are not thread safe (scroll down to the Thread Safety section).
The documentation also states:
However, this is just a by-product of the fact that concurrent reading does not mutate the list. It does not make the type “thread-safe”. Thread-safety is best thought of as offering true support across all actions that define the public contract of the type (in this case, thread-safety in mutating the list also).
More tongue-in-cheek: the implementation of Enqueue doesn’t include any thread synchronisation or locking primitives:
So I’m going with “no”. There is
ConcurrentQueuefor multi-threaded support.