在一个 c# 项目中运行两个 exe 文件

本文关键字:两个 exe 文件 运行 一个 项目 | 更新日期: 2023-09-27 18:31:57


我正在尝试编写一个程序,该程序执行 2 个不同的.exe文件并将其结果输出到文本文件中。当我单独执行它们时,它们工作正常,但是当我尝试同时执行它们时,第二个进程不会运行。谁能帮忙?

这是代码。播放器 1.exe 和播放器 2.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();
        }

    }

在一个 c# 项目中运行两个 exe 文件

1.

你在评论中写道:"该程序甚至没有达到进程2。我通过放置断点来测试这一点。

process1.Start()可能会引发异常。 不要在 process2 设置断点,而是单步执行各行并查找异常。 或者更好的是,添加一个尝试/捕获块并报告错误。

阿拉伯数字。

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

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

3.

如果这些进程没有立即提供数据并结束,则需要在开始等待其 StandardOutput 之前启动它们。 在执行读取之前,请调用每个进程上的Start()

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

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();
    }
}