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
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