Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a synchronized Queue(Of T) in visual basic

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) ?

>Solution :

You can use a ConcurrentQueue(Of T) instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading