Why is SyncLock not working here?

I am working on a class library that will provide asynchronous communication with CLR applications.

SslStream has asynchronous reads (BeginRead) with one callback procedure shared by multiple threads. I do not want callbacks to be processed in parallel during debugging, so I created a critical section:

Private Sub Callback_Read(ByVal ar As IAsyncResult)
   Static OneAtATime As New Object
   SyncLock OneAtATime
      Dim ThisSslStream As SslStream = DirectCast(ar.AsyncState, SslStream)
      ...
   End SyncLock
End Sub

To my surprise, this does not work, at least when I did not set a breakpoint in the SyncLock block. Callbacks for multiple threads simultaneously run inside it, without waiting for an entry point until the previous thread leaves it.

A single step is a nightmare, especially when threads close (close) simultaneously: execute a line for stream 1, execute a line for stream 2, execute the next line for 1, execute the next line for 2, etc. through the whole block.

I thought you might need something more than just a generic “new object”, but then I saw that there is at least one stack overflow answer that illustrates SyncLock just like I use it, only with " Static X as New Object "to create a synchronization object inside a function that should be locked.

Is this because the callback actually comes from the win32 stream outside the .Net framework, which SyncLock doesn't work here?

+4
2

static VB. , , . , shared.

public Class Test
   Private shared SyncRoot As Object = new Object()

   Private Sub Callback_Read(ByVal ar As IAsyncResult)
      SyncLock SyncRoot 
         Dim ThisSslStream As SslStream = DirectCast(ar.AsyncState, SslStream)
         ...
      End SyncRoot
   End Sub

End Class
+2
    Static OneAtATime As New Object

Static - VB.NET. , Visual Basic, , .

, .NET. , VB . MSIL, , . ildasm.exe.

- , . , . , Boolean , . . , [ThreadStatic].

, , SyncLock. :) Shared.

+8

All Articles