Process.Start()导致应用程序挂起

本文关键字:应用程序 挂起 Start Process | 更新日期: 2023-09-27 18:27:27

我和Process.Start()相处得很艰难
这是代码:

static void Main(string[] args)
{
    string fileName = @"C:'path_to_project'bin'Debug'helloworld.exe";
    ProcessStartInfo info = new ProcessStartInfo(fileName);
    info.UseShellExecute = false;
    info.RedirectStandardInput = true;
    info.RedirectStandardOutput = true;
    info.RedirectStandardError = true;
    info.CreateNoWindow = true;
    Process process = Process.Start(info);
    string error = process.StandardError.ReadToEnd();
    string returnvalue = process.StandardOutput.ReadToEnd();
    process.WaitForExit();
    Console.ReadLine();
}

代码应该只调用helloworld控制台应用程序,该应用程序只有一行Console.WriteLine("Hello World"),没有什么特别的。

当我调试这个代码时,我到达了Process process = Process.Start(info);。然后当我点击Step-over(F10)时,什么都没有发生。我的应用程序挂起,我开始的过程就在那里,但还没有结束。我要把他们都杀了。

这段代码在我同事的机器上运行,但在我的机器上进程挂起,我唯一能做的就是终止进程。

我还注意到,当我双击explorer中的任何控制台应用程序时,光标会将状态更改为忙碌,并且在我杀死explorer.exe之前永远不会变回

可能是安全问题或恶意软件?

Process.Start()导致应用程序挂起

Avast Antivirus拦截Process.Start(),可能它试图对我试图启动的应用程序进行沙盒操作,因此它挂起。

我暂时禁用了防护罩,现在它可以工作了。

感谢大家的努力。

所以实际上您的代码看起来不错。它确实适用于我的一个简单的"Hello World!"控制台应用程序。

然而,我记得不久前我们遇到了这样的问题,在我们试图从中获取输出的进程上挂起了process.WaitForExit()

不幸的是,我不记得这是否和你在这里遇到的问题完全一样。但我建议你尝试另一种可能性:

static void Main(string[] args)
{
    string fileName = @"C:'path_to_project'bin'Debug'helloworld.exe";
    ProcessStartInfo info = new ProcessStartInfo(fileName);
    info.UseShellExecute = false;
    info.RedirectStandardInput = true;
    info.RedirectStandardOutput = true;
    info.RedirectStandardError = true;
    info.CreateNoWindow = true;
    StringBuilder outputBuilder = new StringBuilder();
    StringBuilder errorBuilder = new StringBuilder();
    Process process = new Process {StartInfo = info};
    process.OutputDataReceived += (sender, e) => outputBuilder.Append(e.Data);
    process.ErrorDataReceived += (sender, e) => errorBuilder.Append(e.Data);
    process.Start();
    process.BeginErrorReadLine(); // do this after process.Start()
    process.BeginOutputReadLine();
    process.WaitForExit();
    string error = errorBuilder.ToString();
    string returnvalue = outputBuilder.ToString();
    Console.WriteLine("Returned: {0}", returnvalue);
    Console.WriteLine("Error: {0}", error);
    Console.ReadLine();
}

很抱歉,我无法解释为什么您的代码挂起(正如我所说,它对我有效)。但也许这种变化会起作用。