多个过程&等待处理

时间:2012-11-29 18:53:04

标签: .net vb.net event-wait-handle

基于此question我决定尝试使用waithandles / eventwaithandle为我的解决方案基于Jim Mischel建议。我“几乎”让它发挥作用。这是代码

Private Sub InitDeploymentCheck()
moDeploymentCheck = New TRS.Deployment.TRSDeploymentCheck(EnvironmentVariables.Environment, AppDomain.CurrentDomain.BaseDirectory.Contains("bin"), MDIMain)
AddHandler moDeploymentCheck.DeploymentNeeded,
    Sub()
        moTimer = New System.Windows.Forms.Timer()
        moTimer.Interval = 300000 '5 minutes
        moTimer.Enabled = True
        AddHandler moTimer.Tick,
            Sub()
                'check to see if the message box exist or not before throwing up a new one

                'check to see if the wait handle is non signaled, which means you shouldn't display the message box
                If waitHandle.WaitOne(0) Then
                    'set handle to nonsignaled
                    waitHandle.Reset()
                    MessageBox.Show(MDIMain, "There is a recent critical deployment, please re-deploy STAR to get latest changes.", "Critical Deployment", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                    'set the handle to signaled
                    waitHandle.Set()
                End If


            End Sub
        waitHandle.Set()
        MessageBox.Show(MDIMain, "There is a recent critical deployment, please re-deploy STAR to get latest changes.", "Critical Deployment", MessageBoxButtons.OK, MessageBoxIcon.Warning)
    End Sub
End Sub

同样,这是来自几乎所有应用程序都继承自的基本形式。当我们使用单个应用程序时,它可以完美运行。如果您运行的多个应用程序继承自基本表单,并且有人单击其中一个消息框,则有时会在另一个应用程序中显示第二个消息框。我最初把waithandle宣布为静态/共享,并认为这是问题,但事实并非如此。我还尝试让每个应用程序创建自己的等待句柄并将其传递到基础中,这会产生相同的影响。有没有人知道为什么看起来在不同的应用程序之间共享waithandle?哦顺便说一句,waitHandle实际上是一个ManualResetEvent

2 个答案:

答案 0 :(得分:1)

首先,如果要在多个应用程序中使用此功能,则必须使用this constructor创建名为EventWaitHandle的名称,或创建命名对象的其他名称ManualResetEventWaitOne(0)仅适用于单个流程。

其次,命名Mutex可能是更好的解决方案。我刚才意识到我推荐的代码有竞争条件。如果线程A执行Reset并且它成功,然后线程B出现并且在线程A可以调用Mutex之前执行相同的操作,则两个线程将最终显示消息框。

使用WaitOne(0)Mutex可以解决该问题。但请务必发布if (mutex.WaitOne(0)) { try { // do stuff } finally { mutex.ReleaseMutex(); } }

{{1}}

答案 1 :(得分:0)

它无法正常工作的原因是我有一个错误,我在计时器事件之外显示第一个消息框。应该是:

waitHandle.Reset()
MessageBox.Show(MDIMain, "There is a recent critical deployment, please re-deploy STAR to get latest changes.", "Critical Deployment", MessageBoxButtons.OK, MessageBoxIcon.Warning)
waitHandle.Set()