1

我阅读了很多关于锁定机制的材料,但我仍然没有答案如何编写一个:

  • 接受比退出更多的进入
  • 第二个线程将等待最多 5 秒,然后它将进入临界区

以下作品。它处理多次调用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
4

1 回答 1

0

我建议使用System.Threading.ManualResetEvent代替Booleanfor _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
于 2012-08-08T21:03:19.383 回答