I'm trying to create a thread-safe queue of Bytes - One thread receives data from a serial port and puts it into a queue, then the main thread reads the data form the queue and acts on it. Microsoft's .Net documentation suggests using Queue.Synchronized(), however this doesn't seem to work for a Queue(Of T).
Trying the following:
Public Class Form1
#Region "Variables"
Private RxDataUnsafe As Queue(Of Byte) = New Queue(Of Byte)
Private RXData As Queue(Of Byte) = Queue(Of Byte).Synchronized(RxDataUnsafe)
The error I get is: Synchronized is not a member of Queue(Of Byte)
This does work if I remove the (Of Byte)
, which I think gives me a generic queue. I guess this will work for me, but it feels wasteful to be creating a generic type to hold single bytes.
Public Class Form1
#Region "Variables"
Private RxDataUnsafe As Queue = New Queue
Private RXData As Queue = Queue.Synchronized(RxDataUnsafe)
Is there a recommended way to implement a thread-safe Queue(Of T) ?
CodePudding user response:
You can use a ConcurrentQueue(Of T)
instead.