具有进程和模式窗口的背景工作线程
本文关键字:背景 工作 线程 窗口 模式 进程 | 更新日期: 2023-09-27 18:34:37
我正在运行一个进程(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窗口。有什么想法吗?
我怀疑主线程在您的线程有机会运行进程之前会执行检查GetProcessesByName
。要么让主线程等待像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;
您可以在调试器中验证现有条件 - 您会发现由于if
防护,它实际上并没有到达行_wait_debug.ShowDialog();
。 您的主线程通过查找尚未启动的进程来击败工作线程。