-1

我正在尝试编写一个执行 2 个不同的 .exe 文件并将其结果输出到文本文件的程序。当我分别执行它们时,它们工作正常,但是当我尝试同时执行它们时,第二个进程不会运行。任何人都可以帮忙吗?

这是代码。Player1.exe 和 Player2.exe 是返回 0 或 1 的控制台应用程序。

    static void Main(string[] args)
    {
        Process process1 = new Process();
        process1.StartInfo.FileName = "C:/Programming/Tournament/Player1.exe";
        process1.StartInfo.Arguments = "";
        process1.StartInfo.UseShellExecute = false;
        process1.StartInfo.RedirectStandardOutput = true;
        process1.Start();
        var result1 = process1.StandardOutput.ReadToEnd();
        process1.Close();

        Process process2 = new Process();
        process2.StartInfo.FileName = "C:/Programming/Tournament/Player2.exe";
        process2.StartInfo.Arguments = "";
        process2.StartInfo.UseShellExecute = false;
        process2.StartInfo.RedirectStandardOutput = true;
        process2.Start();
        string result2 = process2.StandardOutput.ReadToEnd().ToString();
        process2.Close();

        string resultsPath = "C:/Programming/Tournament/Results/Player1vsPlayer2.txt";
        if (!File.Exists(resultsPath))
        {
            StreamWriter sw = File.CreateText(resultsPath);
            sw.WriteLine("Player1 " + "Player2");
            sw.WriteLine(result1 + " " + result2);
            sw.Flush();
        }


    }
4

2 回答 2

0

我对使用流程了解不多,但是当我需要同时运行单独的东西时,我会使用这种方法。我没有拉入您项目的底部,但请检查一下它是否有任何帮助。

class Program
{
    static void Main(string[] args)
    {
        Process process1 = new Process();
        process1.StartInfo.FileName = "C:/Programming/Tournament/Player1.exe";
        process1.StartInfo.Arguments = "";
        process1.StartInfo.UseShellExecute = false;
        process1.StartInfo.RedirectStandardOutput = true;

        Process process2 = new Process();
        process2.StartInfo.FileName = "C:/Programming/Tournament/Player2.exe";
        process2.StartInfo.Arguments = "";
        process2.StartInfo.UseShellExecute = false;
        process2.StartInfo.RedirectStandardOutput = true;


        Thread T1 = new Thread(delegate() {
            doProcess(process1);
        });

        Thread T2 = new Thread(delegate() {
            doProcess(process2);
        });

        T1.Start();
        T2.Start();
    }

    public static void doProcess(Process myProcess)
    {
        myProcess.Start();
        var result1 = myProcess.StandardOutput.ReadToEnd();
        myProcess.Close();
    }
}
于 2013-09-19T19:52:27.377 回答
0

1.

您在评论中写道:“该程序甚至没有到达 process2。我通过设置断点对其进行了测试。”

process1.Start()可能会抛出异常。与其在 process2 处设置断点,不如逐行查找异常。或者更好的是,添加一个 try/catch 块并报告错误。

2.

另一种可能性是ReadToEnd行为不符合预期。您可以Peek通过这样的循环查看是否有更多数据要读取:

var result1 = new StringBuilder()
while (process1.StandardOutput.Peek() > -1)
{
   result1.Append(process1.StandardOutput.ReadLine());
}

3.

如果这些进程没有立即提供数据并结束,那么您需要在开始等待它们的 StandardOutput 之前让它们都启动。Start()在读取之前调用每个进程。

于 2013-09-19T19:23:40.940 回答