我有一个方法可以在我的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();
}
我有一些进程漫游的问题。由于多线程进程的调试非常困难,而且导致这种情况的原因我并不清楚,您有任何想法吗?为什么有些进程会从我的陷阱中逃脱?