在控制台应用程序、Windows 10、Visual Studio 2015、.NET 4.6 中,我在 Main 中调用称为 TestProcess 的单个方法。构建模式调试,如果我在不调试的情况下运行应用程序,它会打印正确的文本:
827ccb0eea8a706c4c34a16891f84e7b *test.txt
按任意键继续 。. .
如果我在调试的情况下运行应用程序,它会在打印前等待 3 秒
错误 假 假 假 '' ''
这只是对实际问题的简化,此代码是一些复杂代码的主干,这些代码在没有调试 md5sums.exe 的情况下也挂在发布中,但适用于其他一些程序。Coplex 代码也挂在var a = proc.WaitForExit(timeout); 直到超时,如附件示例所示。另一方面,这种简化将在没有调试器的版本中起作用。此外,所有这些问题都始于 Windows 10,在 Windows 7 上一切正常。
[编辑] 不明白为什么md5sums.exe会导致问题,如果我使用其他东西,即。FileName = "ping", Arguments = "localhost" 一切都按预期工作。
[EDIT2] 我的复杂程序在 Windows 10 上停止工作(发布 - 不带调试运行),但这个示例也挂在 Windows 7 上(调试 - 带调试运行)
static void TestProcess()
{
using (var proc = new Process())
{
proc.StartInfo.FileName = "md5sums.exe";
proc.StartInfo.WorkingDirectory = @"C:\Temp\ProcessDebug";
proc.StartInfo.Arguments = "-u test.txt";
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
proc.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
outputWaitHandle.Set();
else
output.AppendLine(e.Data);
};
proc.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
errorWaitHandle.Set();
else
error.AppendLine(e.Data);
};
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
var timeout = 1000;
var a = proc.WaitForExit(timeout);
var b = outputWaitHandle.WaitOne(timeout);
var c = errorWaitHandle.WaitOne(timeout);
if (a && b && c)
Console.WriteLine(output.ToString());
else
Console.WriteLine($"Error {a} {b} {c} '{output}' '{error}'");
}
}
}