0

I want to use a shared list (ConcurrentQueue<T>) for my project, that includes a listener, a processor and a sender. The listener enqueues items to a list, the sender dequeues them from the same list (FIFO). The processor does some processing in between.

The idea is to start the listener and sender asynchronously and the processor synchronously, but they all access the same data structure (the ConcurrentQueue<T>).

Can I simply declare a static ConcurrentQueue<T> or do I need some locking strategy to avoid resource contention? My understanding is the ConcurrentQueue<T> is thread safe and I assume no other code is required. Is my understanding correct?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
ChrisB
  • 37
  • 3
  • 9
  • 4
    "locking" and "**avoid** resource _contention_" doesn't sound right. You might want provide more details or some actual code about what you have so far. Generally, `ConcurrentQueue` doesn't require any additional locking to protect the data structure itself. About the items you put in there, you have to take care yourself. – Christian.K Apr 20 '21 at 07:39
  • I feel like your question is about the field storing the `ConcurrentQueue` rather than using the queue itself. With that in mind, does this answer your question? [Is the C# static constructor thread safe?](https://stackoverflow.com/questions/7095/is-the-c-sharp-static-constructor-thread-safe) – ProgrammingLlama Apr 20 '21 at 07:40
  • 1
    You can use `static ConcurrentQueue`, however, I would urge you to have a look at `Channels` https://devblogs.microsoft.com/dotnet/an-introduction-to-system-threading-channels/ – JohanP Apr 20 '21 at 07:42
  • 1
    I would add that creating [mutable global state](https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil) like this is probably not a good idea. – JonasH Apr 20 '21 at 08:28
  • "The processor does some processing in between." implies you need two queues. Otherwise there is nothing stopping the sender from picking up an item which the processor is not finished processing. – Ben Voigt Aug 04 '23 at 18:49

0 Answers0