gpt4 book ai didi

c# - Dotnet core 2进程启动超时

转载 作者:行者123 更新时间:2023-11-30 12:55:35 25 4
gpt4 key购买 nike

我有一种方法可以从 dotnet core 2 中的 c# 代码启动进程。此方法如下所示:

    internal static string[] RunCommand(string filename, string args, string workingDirectory = null)
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = filename,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
//WindowStyle = ProcessWindowStyle.Hidden
}
};

if (workingDirectory != null)
{
proc.StartInfo.WorkingDirectory = workingDirectory;
}

//Console.WriteLine(proc.StartInfo.FileName + " " + proc.StartInfo.Arguments);

List<string> lines = new List<string>();

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{

lines.Add(line);
}
}
proc.Dispose();

return lines.ToArray();
}

问题是一些启动的进程陷入了循环,这让我的 vps 遇到了问题。

那么问题是有什么解决方案可以运行有截止日期的进程吗?

更新

根据“Jacek Blaszczynski”的推荐,我尝试了以下代码:

    internal static string[] RunCommand(string filename, string args, string workingDirectory = null, int timeoutInSeconds = 60)
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = filename,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
//WindowStyle = ProcessWindowStyle.Hidden
}
};

if (workingDirectory != null)
{
proc.StartInfo.WorkingDirectory = workingDirectory;
}

//Console.WriteLine(proc.StartInfo.FileName + " " + proc.StartInfo.Arguments);

List<string> lines = new List<string>();

bool isKilled = false;

new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
Thread.Sleep(timeoutInSeconds * 1000);
try
{
if (proc != null && !proc.HasExited)
{
isKilled = true;
proc.Kill();
Console.WriteLine("Annoying process killed.");
}
}
catch
{
// just let it go
}
}).Start();

try
{
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{

lines.Add(line);
}
}
proc.Dispose();
}
catch
{
// just look what happens
}

return isKilled ? new string[] { "" } : lines.ToArray();
}

但我仍然有一些徘徊的过程。由于多线程进程的调试非常困难,导致这种情况的情况我也不知道,你知道为什么某些进程会从我的陷阱中逃脱吗?

最佳答案

首先,我需要对缺失信息做出一些假设:(i) 您在 Windows 上运行代码,(ii) 您的进程没有图形用户界面(窗口)。有两种推荐的方法来停止 Windows 进程,首选方法取决于进程类型:(i) GUI 进程,(ii) 非 GUI 进程。在第二种情况下,您应该调用 Process.Kill() 方法让可靠的进程立即退出,然后立即调用 Process.WaitForExit()。 Microsoft 文档指出:

Kill is the only way to terminate processes that do not have graphical interfaces.

它不会让您免于清理进程资源(DisposeClose 调用),但是,此任务在某种程度上与 Process.Kill() 正交 根据文档可能会导致:

Data edited by the process or resources allocated to the process can be lost if you call Kill.

有许多不同的异常可能会被抛出,因此除了基本的异常处理代码之外,还需要一些其他的代码。

关于c# - Dotnet core 2进程启动超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47517455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com