Pinidbest
Pinidbest

Reputation: 4316

C# queue - do I need concurrency

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?

Upvotes: 0

Views: 71

Answers (2)

dyz
dyz

Reputation: 127

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.

Upvotes: 3

SUNIL DHAPPADHULE
SUNIL DHAPPADHULE

Reputation: 2863

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

Upvotes: 1

Related Questions