Search code examples
vb.netmultithreadingobjectthread-safetysynclock

VB.net SyncLock Object


I always seen on SyncLock examples people using

    Private Lock1 As New Object ' declaration
    SyncLock Lock1 ' usage

but why? In my specific case I'm locking a Queue to avoid problems on mult-threading Enqueueing and Dequeueing my data.

Can I lock the Queue object itself, like this?

    Private cmdQueue As New Queue(Of QueueItem) ' declaration
    SyncLock cmdQueue ' usage

Any help appreciated. Thanks.

edit:

thanks for all the answers, but tcarvin answer was what I was looking for. The queue is private from my singleton Comms object that queues new messages to be sent (exposed by a Send method), the queue is consumed in a worker thread within this object one message at a time and the only code I have inside the locks are one call to Enqueue and Dequeue.


Solution

  • Sage advice from the other posters for sure. But the answer is Yes, you can use the Queue object to lock on. You can use any object. And in your code snippet you declared your queue instance private so you are likely to avoid th common issue of someone else locking on your queue object (assuming you don't pass the object outside your class). Best-practices though suggest using a dedicated object such that, down the road, someone doesn't change your code and then expose that queue object being used for locking.