.NET Is Queue.Enqueue thread safe?

Let's say that I have a module in which there is a queue.

For other Enqueue objects, they must go through a function:

public sub InsertIntoQueue(Obj)
    MyQueue.Enqueue(Obj)
end sub

If I have multiple threads running and they want to call InsertIntoQueue (), is this considered thread safe?

I get the impression that only one copy of the instructions needed to execute the InsertIntoQueue () function is required in memory ... which would make me think that it is thread safe.

However, I wonder what happens when two threads try to run a function at the same time.

Is this thread safe, and if not, how can I make it thread safe? (and what would be the implications for memory performance and speed)

+5
source share
6 answers

Use Queue.Synchronized wrapper.

+8
source

No, this is not thread safe.

Public static (Shared in Visual Basic) elements of this type are safe for multithreaded operations. Instance members do not guarantee thread safety.

From the MSDN website .

I would suggest adding an object to represent the synchronization descriptor for your object

Dim SyncHandle as Object = new Object()

And change your method as such

Public Sub InsertIntoQueue(Object item)
    SyncLock SyncHandle 
       MyQueue.Enqueue(item)
    End SyncLock
End Sub
+4
source

do

SyncLock MyQueue
   MyQueue.Enqueue(Obj)
End SyncLock

Sub

+2

, . , .

, , , , . .NET, Queue, , thmeselves.

, , , - . , -

+1

OP, . , , , , , , ?

dequeue, , , dequeue ( ), , ( a) , ( b), , , dequeue, a .

, dequeue - .

This , this / this, vb.net, .

0

, .

(, ), , , . - ( MSDN):

( Visual Basic) . .

, , , MyQueue.Enqueue(Obj) :

  • ();
  • ;

, , , , , , , .

, , , Enqueue() Queue.Synchronized() , , , , Queue ( , , ):

Private ReadOnly Property MyQueue() as Queue
Get
    SyncLock (m_myQueueLock)
        Return m_myQueue
    EndSyncLock
End Get
End Property

, !

0

All Articles