backgroundWorker with Process and modal window

时间:2016-02-13 15:49:30

标签: c# backgroundworker

我正在运行一个进程(exe文件),同时我想要等待'弹出窗口。 使用BGW:

public void RunDesign()
{
     BackgroundWorker m_oWorker = new BackgroundWorker();
     m_oWorker.DoWork += new DoWorkEventHandler(m_oWorker_DoWork);
     m_oWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_oWorker_RunWorkerCompleted);
     m_oWorker.RunWorkerAsync();

     // I want the following pop up window to be shown, while my exe file is running
     wait_debug _wait_debug = new wait_debug();
     Process[] ExeName = Process.GetProcessesByName("AB"); //this is the exe file
     if (ExeName.Length == 1)
     {
           _wait_debug.ShowDialog(); // Show() doesn't work either
           _wait_debug.TopMost = true;
     }
}

m_oWorker.DoWork方法中,我使用p.StartInfo运行我的流程,但运行正常。 我的问题是没有显示wait_debug窗口。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我怀疑主线程在您的线程有机会运行该进程之前执行了检查ManualResetEvent。让主线程等待同步对象(如GetProcessesByName)或仅循环直到// NOTE: this loop will block your main GUI thread so it might be // a good idea not to wait too long by having a timeout mechanism Process process=null; do { Thread.Sleep(0); // be nice to CPU Process[] items = Process.GetProcessesByName("AB"); //this is the exe file if (items.Length == 1) { process = items[0]; } // break if taking too long } while (process == null); // if process is still null then we timed out. handle appropriately _wait_debug.ShowDialog(); // Show() doesn't work either _wait_debug.TopMost = true; 实际返回某些内容。

这是一个简单的解决方法:

_wait_debug.ShowDialog();

您可以在调试器中验证现有条件 - 由于if警卫,您会发现它实际上并未到达{{1}}行。通过查找尚未启动的进程,您的主线程击败了工作线程。