Question

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.

Was it helpful?

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.

OTHER TIPS

This is a common misconception about locks. The job of a lock is to block code, not to impart thread-safety on an object. The object is there only to keep track of the state of a lock. And since you want to block a specific bit of code, you'll need a specific object to store the lock state. A public queue is not nearly specific enough, it is bound to be used by other code somewhere else. And if it also mis-uses the queue object to block its own code then the odds for a nasty deadlock problem are high.

The notion of locking objects to implement thread safety actually exists, it is the subject of intense research that just never seems to get to my machine. It is called STM, "software transactional memory". Wikipedia article is here.

The problem is others can lock your object and it would be outside of your control. See Microsoft's best practice on this lock statement

I think that what you do is bad practice , since the locked object must remain unchanged. Since you lock on a Queue(Of QueueItem) and then you Dequeue from the same Queue , then the object changes and, as stated here : https://msdn.microsoft.com/en-us/library/3a86s51t.aspx (2nd rule) ,

The mechanism requires that the lock object remain unchanged.

So you should do like this Public StatusObject As New Object and lock on it

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top