Threading - Avoiding running a Routine 2x [VB.Net]

NeuralJack

Centurion
Joined
Jul 28, 2005
Messages
138
I usually work with many threads. But more often than not I do not want those threads to hit the same routine at the same time. Currently here's what I do. If any of you have a more effective/efficient way let me know. For all i know VB has some sort of property a subroutine can have that only allows it to be accessed by one thread at a time.

Visual Basic:
Public RoutineIsRunning As Boolean = False

Public Sub RoutineOfInterest()
If RoutineIsRunning = False Then
RoutineIsRunning = True
     '
     ' The Code for this routine
     '
RoutineIsRunning = False
End If
End Sub
 
The way you are currently doing it isn't guaranteed to prevent 2 threads running the routine at the same time - it is perfectly possible for 1 thread to query RoutineIsRunning and see it is false, lose it's timeslice and another thread to query the value and also see it as false.

The easiest way (although not necessarily the most efficient) is to do something like
Visual Basic:
Dim o As New Object

    Public Sub RoutineOfInterest()

        System.Threading.Monitor.Enter(o)
        '
        ' The Code for this routine
        '
        System.Threading.Monitor.Exit(o)

        'or 

        SyncLock o
            '
            ' The Code for this routine
            '
        End SyncLock
    End Sub
 
Last edited:
Thanks, i'm starting to think you guys could improve every code i've written hehe. Anyway, SyncLock is great. I wonder though if the LockObject (o) should be declared outside of the RoutineOfInterest?



PlausiblyDamp said:
The way you are currently doing it isn't guarenteed to prevent 2 threads running the routine at the same time - it is perfectly possible for 1 thread to query RoutineIsRunning and see it is false, lose it's timeslice and another thread to query the value and also see it as false.

The easiest way (although not necesarily the most efficent) is to do something like
Visual Basic:
    Public Sub RoutineOfInterest()
        Dim o As New Object
        System.Threading.Monitor.Enter(o)
        '
        ' The Code for this routine
        '
        System.Threading.Monitor.Exit(o)

        'or 

        SyncLock o
            '
            ' The Code for this routine
            '
        End SyncLock
    End Sub
 
Back
Top