Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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.

 

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

Currently Using: Visual Basic.Net 2005, .Net Framework 2.0
  • Administrators
Posted (edited)

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

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

Edited by PlausiblyDamp

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Posted

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?

 

 

 

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

   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

Currently Using: Visual Basic.Net 2005, .Net Framework 2.0

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...