我阅读了很多关于锁定机制的资料,但我仍然没有回答如何写一个:
以下作品。它处理多次调用 ThreadA_Method1 的情况,然后(有时)紧跟 ThreadA_Method2 。 但有没有更好的解决方案?
Private _lock as Boolean
Private Sub ThreadA_Method1 Handles _otherDll.BeforeAction
_lock = True
' A - Critical section code 1
' ...
End Sub
Private Sub ThreadA_Method2 Handles _otherDll.AfterAction
Try
' A - Critical section code 2
' ...
Finally
_lock = False
End Try
End Sub
Private Sub ThreadB_Method
Dim stopWatch As Stopwatch = New Stopwatch()
stopWatch.Start()
While _lock AndAlso stopWatch.ElapsedMilliseconds < 5000
Thread.Sleep(100)
End While
stopWatch.Stop()
' B - Critical section code
' ...
End Sub
答案 0 :(得分:0)
我建议使用System.Threading.ManualResetEvent
代替Boolean
_lock
(参见http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(v=vs.80).aspx)。然后,您可以使用WaitOne
方法更有效地暂停。
Private _lock As New ManualResetEvent(False)
Private Sub ThreadA_Method1() Handles _otherDll.BeforeAction
_lock.Reset()
' A - Critical section code 1
' ...
End Sub
Private Sub ThreadA_Method2() Handles _otherDll.AfterAction
Try
' A - Critical section code 2
' ...
Finally
_lock.Set()
End Try
End Sub
Private Sub ThreadB_Method()
_lock.WaitOne(5000)
' B - Critical section code
' ...
End Sub