NeuralJack Posted August 3, 2006 Posted August 3, 2006 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 Quote Currently Using: Visual Basic.Net 2005, .Net Framework 2.0
Administrators PlausiblyDamp Posted August 3, 2006 Administrators Posted August 3, 2006 (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 March 12, 2007 by PlausiblyDamp Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
NeuralJack Posted August 3, 2006 Author Posted August 3, 2006 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 Quote Currently Using: Visual Basic.Net 2005, .Net Framework 2.0
Administrators PlausiblyDamp Posted August 3, 2006 Administrators Posted August 3, 2006 Good catch, just declare the object outside of the routine and it should work fine. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.