Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is Queue.Count thread safe?

Tags:

c#

I need one thread to modify Queue (both adding and removing elements) and another thread only to call Queue.Count. Would it be safe or I need to use locks or ConcurrentQueue?

like image 251
Oleg Vazhnev Avatar asked Jan 19 '23 02:01

Oleg Vazhnev


2 Answers

The Queue property is not thread-safe, as per the docs.

But it is an atomic int, the worst that could happen is that you read the wrong (outdated) value. Which may or may not be a problem.

But since you'll have to do something to prevent your reading thread from caching the value you might as well lock().

like image 109
Henk Holterman Avatar answered Jan 29 '23 12:01

Henk Holterman


Queue does not provide thread safety guarantees, so yes you do need one of the two alternatives you mention.

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

A Queue(Of T) can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

like image 23
Jon Avatar answered Jan 29 '23 10:01

Jon