vb.netmultithreadingasynchronoussynchronizationsynclock

Should I use SyncLock or Interlocked?


Can someone help me understand how synclock statements work? I know there are some other posts about synclock here but I was not able to follow the answers very well. I am trying to get a simple multithreading example up and running but am having trouble. At first I tried the following code.

Public Class Class1
    Public list As List(Of Integer) = New List(Of Integer)

    Public Sub addInt(ByVal i As Integer)
        SyncLock list
            list.Add(i)
        End SyncLock
    End Sub

    Public Sub MainLoop()
        While list.Count < 50
            SyncLock list
                For Each i As Integer In list
                    Debug.WriteLine(i.ToString())
                Next
            End SyncLock
        End While
    End Sub
End Class

I had a simple winform with two buttons. I used the first button to create a obj of Class1 and start the MainLoop method in a new thread. And I used the seconded button to call the addInt method. However the code might work for a press or two and then lock up. After reading the other questions from this form I realized that the lockobject for the synclock statement did not work as I initially thought, and was just an arbitrary reference object that should not ever be changed. I think the syncLock statement just forces the whole code block to execute before passing processor control to a new thread. So I tried this using another lock object but now it just locks up.

Public Class Class1
    Private padLock As String = "PADLOCK"
    Public list As List(Of Integer) = New List(Of Integer)

    Public Sub addInt(ByVal i As Integer)
        SyncLock padLock
            list.Add(i)
        End SyncLock

    End Sub

    Public Sub MainLoop()
        While list.Count < 50
            SyncLock padLock
                For Each i As Integer In list
                    Debug.WriteLine(i.ToString())
                Next
            End SyncLock
        End While
    End Sub
End Class

Can someone explain why the above code does not work? In a similar post someone mentioned that the Interlocked class would be useful but I could not figure out what that is or how that is used. A brief "Interlocked Class For Dummies" explanation would also be appreciated.


Solution

  • Ok I think I figured out the problem. I don't think my thread was deadlocking I think it was just starving my Application.Run() Thread of resources. When I added a Thread.Sleep(500) call after the End SyncLock in the MainLoop method the program worked as expected.