Announcement

Collapse
No announcement yet.

SyncLock in HS VB.Net script

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    SyncLock in HS VB.Net script

    Within a HS2 vb.net script how does one provide a thread-safe block of code (critical section) within a method? The following snippet doesn't work as the Shared keyword causes a compile error in the context of the module.

    Does one need to SyncLock on an object that is obtained with hs.CreateVar() and hs.GetVar()?

    Code:
    Shared myLock As New Object
    
    Sub mySub(ByVal param As String)
        SyncLock(myLock)
            'Do thread safe stuff here....
        End SyncLock
    End Sub
    Thanks,
    Don
    Last edited by dschoppe; December 1, 2012, 10:59 AM.

    #2
    Through testing I verified that hs.CreateVar, hs.SaveVar, and hs.GetVar can be used in lieu of declaring a "Shared" object for SyncLock.

    Just call a method like this once, for example at HS startup, to create an object and store it in a HS variable:

    Code:
    Public Sub CreateSaveMyLock(ByVal param As String)
        Dim result As String = hs.CreateVar("myLock")
        If result <> "" Then
            hs.WriteLog("Error", "hs.CreateVar() returned " & result)
        Else
            Dim lockObj As Object = New Object()
            result = hs.SaveVar("myLock", lockObj)
            If result <> "" Then
                hs.WriteLog("Error", "hs.SaveVar() returned " & result)
            Else
                hs.WriteLog("Info", "Created and saved lockObj in HS variable named ""myLock""")
            End If
        End If
    End Sub

    Then get the object from the HS variable and use it as the SyncLock target to ensure only one thread at a time can execute protected statements:

    Code:
    Public Sub MySub(ByVal param As Object)
            Dim lockObj As Object = hs.GetVar("myLock")
            SyncLock (lockObj)
                'Do thread safe stuff here....
            End SyncLock
    End Sub
    Cheers,
    Don

    Comment

    Working...
    X