4
  public void ExecuteProcessChain(string[] asProcesses, string sInRedirect, string sOutRedirect)
    {
            Process p1 = new Process();
            p1.StartInfo.UseShellExecute = false;
            p1.StartInfo.RedirectStandardOutput = true;
            p1.StartInfo.FileName = asProcesses[0];
            p1.Start();
            StreamReader sr = p1.StandardOutput;
            string s, xxx = "";
            while ((s = sr.ReadLine()) != null)
                Console.WriteLine("sdfdsfs");
                //xxx += s+"\n";
            p1.StartInfo.RedirectStandardInput = true;
            p1.StartInfo.RedirectStandardOutput = false;
            p1.StartInfo.FileName = asProcesses[1];
            p1.Start();
            StreamWriter sw = p1.StandardInput;
            sw.Write(xxx);
            sw.Close();
            sr.Close();

    }

我正在尝试执行“calc|calc”,但是当我这样做时,它会卡在行上while ((s = sr.ReadLine()) != null),只有在我关闭计算器后代码才会继续。我需要两个计算器一起工作。你知道怎么做吗?

4

2 回答 2

1

ReadLine正在从第一个计算的输出中读取。Calc 不发送任何输出。因此,ReadLine将永远不会返回,因此下一次计算将不会开始。当第一个计算终止时,ReadLine不能再从第一个计算中读取,因此返回 null。返回后,代码可以开始第二次计算。

您可以不从第一个计算中读取或异步读取。您可能想参考Async ReadLine了解如何异步读取。

您也可以在开始调用之前使用 p2 开始第二次计算ReadLine

于 2011-03-03T08:40:13.243 回答
0

为什么不使用线程?

考虑一下:将每个 calc 放入一个线程中,然后同时启动它们。之后让程序等待他们。只有在两个线程都完成了它们的工作(读取数据)之后,你才能继续。

请记住,线程不能直接更改来自另一个线程的数据,因此我可能会建议使用 Invoke 或静态变量,具体取决于您可能需要什么。

如果可能的话,你可以使用已经有一些有用的方法来帮助你的任务/并行库。

后台工作人员也是一种方法。

于 2011-03-03T19:32:22.923 回答