如何编写接受多个输入的VB线程锁定代码?

时间:2012-08-08 17:28:46

标签: .net vb.net thread-synchronization

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

  • 接受更多输入而不是退出
  • 第二个线程将等待最多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

1 个答案:

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