启动进程并等待退出代码而不冻结

时间:2014-03-23 07:32:36

标签: c# .net winforms process exit-code

我试图将我曾经在NSIS中创建的程序移植到 C#Winforms ,我遇到了一个问题,当我调用进程时,adb.exe,整个程序锁定然后只是几秒后抛出我的最终输出。

我意识到这可能已被问过很多次了,但即使经过大量的谷歌搜索,我仍然无法自己找到解决方案(加上我使用WinForms的新手)。以下是我的代码:

public static int runAdb(string args, out string output)
{
    bAdbRunning = true;

    adbProc.StartInfo.Arguments = args;
    adbProc.Exited += new EventHandler(adbExitHandler);
    adbProc.Start();

    // Read all output into string output
    output = adbProc.StandardOutput.ReadToEnd();

    while (bAdbRunning)
    {
        System.Threading.Thread.Sleep(100);
    }

    return adbProc.ExitCode;
}

private static void adbExitHandler(object sender, EventArgs args)
{
    bAdbRunning = false;
}

这就是调用它的代码:

public static void BaseOperations(Label outputWindow, ProgressBar operationsBar, int opIndex)
{
    // Run server
    if (opIndex == 0)
    {
        outputLine(outputWindow, "Shutting down existing adb server");
        runAdb("kill-server", out outText);
        operationsBar.Value += 1; // 1%

        outputLine(outputWindow, "Restarting adb server...");
        runAdb("start-server", out outText);
        operationsBar.Value += 1; // 2%;
    }
}

1 个答案:

答案 0 :(得分:2)

您需要订阅流程Exited事件才能实现此目标。

试试这个:

public static int runAdb(string args, out string output)
{
    adbProc.StartInfo.Arguments = args;
    adbProc.Exited += new EventHandler(ProcessExitHandler);
    adbProc.Start();

    // Read all output into string output
    output = adbProc.StandardOutput.ReadToEnd();        
}

private void ProcessExitHandler(object sender,EventArgs args)
{

//Your process exited and now do whatever you want.

}