当前表单的 UI 在创建进程以初始化 cab 安装程序时冻结

Current form's UI freezes while creating a process to initialize cab installer

我有一个表格可以启动一个进程来初始化 cab 安装。创建进程并 运行ning 时,我当前的 UI 冻结(我有一个加载图标 运行ning 使用线程计时器)。

//When the form initializes, the following timer is created to start the animation
System.Threading.TimerCallback TimerDelegate = new System.Threading.TimerCallback(animationTimer);
timer = new System.Threading.Timer(TimerDelegate, null, 0, 100);

//After i started the following snippet to create a process to start cab installation, the animation freezes in my current Form
ProcessInfo pi = new ProcessInfo();
byte[] si = new byte[128];
string szImageName = "\Windows\wceload.exe";
string destPath = swPath;
string szCmdLine = @"/noaskdest /noui " + (char)34 + destPath + (char)34;
bool result = CreateProcess(szImageName, szCmdLine, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, IntPtr.Zero, si, pi);
System.Threading.Thread.Sleep(100);
if (result == true)
{
       int waitResult = 0;
       waitResult = WaitForSingleObject(pi.hProcess, INFINITE);
       CloseHandle(pi.hThread);
       CloseHandle(pi.hProcess);

       label1.Text = "Update is complete. Rebooting device...";
       label1.Refresh();
       System.Threading.Thread.Sleep(1000);
       SetSystemPowerState(IntPtr.Zero, 0x00800000, 0x00001000);

}

如何确保当前表单上的动画继续 运行,同时创建的进程 运行ning?请指教,谢谢

根据 Timer 的实现方式,它可能会被阻止。如果计时器在内部使用 WM_TIMER 消息,就会出现这种情况。这些消息必须由消息处理程序处理,但是当消息泵不可用时,如代码阻塞时,计时器将不会被执行。

您需要在单独的线程中启动 Process 和 WaitForSingleObject 调用。因此 WaitFor 不会阻止您的 UI 代码(使用消息泵)。

您可以实现委托和事件处理程序,以便线程可以更新 UI。然后在 WaitForSingleObject 中不要使用 INFINITE,而是使用 TimeOut 值,然后在 case switch 中检查等待结果。如果它是 WAIT_TIMEOUT,您可以使用它来更新 UI(使用事件处理程序)。

您可以使用 this 作为线程和 GUI 更新的起点。但是还有其他关于如何做到这一点的好资源。