在一个c#项目中运行两个exe文件
我正在尝试编写一个程序,执行两个不同的.exe文件,并将其结果输出到一个文本文件。当我分别执行它们时,它们工作正常,但当我尝试同时执行它们时,第二个进程不会运行。有人能帮忙吗 这是代码。Player1.exe和Player2.exe是返回0或1的控制台应用程序在一个c#项目中运行两个exe文件,c#,console,exe,C#,Console,Exe,我正在尝试编写一个程序,执行两个不同的.exe文件,并将其结果输出到一个文本文件。当我分别执行它们时,它们工作正常,但当我尝试同时执行它们时,第二个进程不会运行。有人能帮忙吗 这是代码。Player1.exe和Player2.exe是返回0或1的控制台应用程序 static void Main(string[] args) { Process process1 = new Process(); process1.StartInfo.FileName
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();
}
}
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.
如果这些过程没有立即提供数据并结束,那么您需要在开始等待它们的标准输出之前启动它们。在执行读取操作之前,对每个进程调用
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();
}
}
您的代码已经是这样工作的,ReadToEnd()直到进程退出才完成。很难猜出你为什么要问这个问题。这个程序甚至没有到达process2。我通过设置断点来测试它。在线程上定义断点,然后启动它们。惊讶VS没有发脾气,你没有逃脱你的束缚。尝试“C://Programming//Tournament//Player2.exe”@scnrio反斜杠需要加倍或以符号和开头。正斜杠看起来很好用。我认为如果出现问题,process1不会单独运行。当我评论process2部分时,process1工作得很好。刚开始看起来很滑稽,但你是对的。我看看能不能想出一个解决问题的办法you@Lusine好。问题是1、2还是3?有机会时接受答案。每个人都喜欢假互联网积分;)