2012-11-29 54 views
0

基于此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实际上是一个ManualResetEvent

+0

你是如何创建waitHandle的? – usr

+0

@usr:只是在类的顶部的一个私有变量Dim waitHandle作为新的ManualResetEvent(True) – coding4fun

回答

1

首先,如果你想在多个应用程序中使用它,你将不得不使用this constructor创建一个名为EventWaitHandle,或者创建一个命名对象。 A ManualResetEvent只适用于单个进程。

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

使用MutexWaitOne(0)将解决该问题。一定要释放Mutex,虽然:

if (mutex.WaitOne(0)) 
{ 
    try 
    { 
     // do stuff 
    } 
    finally 
    { 
     mutex.ReleaseMutex(); 
    } 
} 
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()