locked
[HELP] Threading issue in VB RRS feed

  • Question

  • We have a stored procedure that executes in a long time so we decided to enclose it in a thread. Before executing the long stored procedure, the procedure should be locked so that only one user can execute the thread. However, I have noticed that a user can still execute twice. Here is the code.

    Private Sub RunThread()
    Dim ProcessThread As Thread = New Thread(AddressOf DoProcess)
    DoProcess.Start()
    ...
    End Sub
    Private Shared lock as Object = New Object()
    Private sub DoProcess
    Try
    Monitor.TryEnter(lock)
    LockProcess() 'Inserts record in sp to denote that process is locked
    Process() 'Long running Stored procedure
    UnlockProcess() 'Updates newly inserted record in sp to unlock the process
    ...
    Catch ex As Exception
    Throw New Exception("Error: " + ex.Message)
    Finally
    Monitor.Exit(lock)
    End Try
    End Sub

    The problem is when I tested the code by opening two browsers then simultaneously process, two records are being inserted into our lock table. The second user should not be able to process because the DoProcess is already locked. Can you help me what went wrong in my code. Thanks
    Tuesday, October 12, 2010 10:52 AM

Answers

  • This is not a threading issue, it's your environment your running your code in. Each individual web browser runs a different copy of the same code in different process spaces and therefore allows this to happen. As far as your program is concerned each copy is a seperate instance of the program running in your web browser and as such isn't related to each other. Thus, the lock from one copy running is a different variable to the lock in the other copy and therefore, as they are not the same, it'll allow both to work simutaniously.

    What you need to look into is a Mutex. These can shared between programs and once a mutex is set, can be examined by other processes to it's state. You need to signal the mutex state when one instance takes control, then unlock when done:

    http://www.developerfusion.com/article/5184/multithreading-in-vbnet/4/

    Hopefully this will guide you to using the correct object for the task at hand.

    Tom.

    • Marked as answer by Liliane Teng Wednesday, October 20, 2010 2:49 PM
    Tuesday, October 12, 2010 11:17 AM