C# queue - do I need concurrency

Asked by At

In case 2 different threads are enqueuing and dequeuing to and from a queue. Why do I need to use concurrency Queue. One is pulling out of the structure and one pushing I.

Why is thread safety important here? Due to the internal structure?

2 Answers

3
dyz On Best Solutions

You can It's necessary to use ConcurrentQueue. For example, suppose the two threads are pushing and popping the same item. The reading thread sees that there's an item in queue, but the writing thread hasn't finished writing it yet: now the reading thread has read junk.

Edit: Alexei is right, you can implement your own instead of using ConcurrentQueue. But I'd recommend against it as the library implementation is likely better than what you can create.

1
Sunil Dhappadhule On

I suggest you ConcurrentQueue<T> The concurrent queue designed to accept multiple threads reading and writing to the queue without you need to explicitly lock the data structure