Question about Synclock and exceptions

C

Chris Dunaway

I was using a Queue object like this to create my own specialized queue
class for use with my own objects:

Public Class MySpecializedQueue

Private q As New Queue

Public Sub Enqueue(obj As MyCustomClass)
SyncLock q.SyncRoot
q.Enqueue(obj)
End SyncLock
End Sub

Public Function Dequeue() As MyCustomClass
SyncLock q.SyncRoot
Return DirectCast(q.Dequeue, MyCustomClass)
End SyncLock
End Function

End Class

What happens if there is an exception inside the SyncLock block for
some reason? Will the q now be locked to other threads? Or does the
End Synclock automatically happen?

Chris
 
J

Jay B. Harlow [MVP - Outlook]

Chris,
What happens if there is an exception inside the SyncLock block for
some reason? Will the q now be locked to other threads? Or does the
End Synclock automatically happen?
Yes.

SyncLock is basically a Try/Finally block with calls to Monitor.Enter &
Monitor.Exit.

So SyncLock is effectively Monitor.Enter & a Try, while End SyncLock is
effectively Finally with Monitor.Exit...

You can use ILDASM.EXE to see the actual IL generated.

Hope this helps
Jay
 
C

Chris Dunaway

Thanks Jay,

Is there any way to check to see if an object is currently locked? If
a thread has entered a syncLock, is there a way to find out which
thread has the lock?

Just wondering
 
J

Jay B. Harlow [MVP - Outlook]

Chris,
Is there any way to check to see if an object is currently locked?
You can use Monitor.TryEnter to see if an object is currently locked.
However it will give you the lock if it is currently not owned.
If
a thread has entered a syncLock, is there a way to find out which
thread has the lock?
Non that I know of. With effort you could probably create your own class
that supports knowing who has the lock... However even then you may have
race conditions or performance conditions...

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Shared Variable used as SyncLock 1
Synclock 1
Thread Sync Queue Problem 2
SyncLock question. 1
writing to file from web service 5
Singletons and Terminal server 3
Synclock Questions 2
Monitor.Pulse Methos 2

Top