【发布时间】:2018-05-11 01:50:28
【问题描述】:
我有一种方法可以从 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();
}
但我仍然有一些徘徊过程。由于多线程进程的调试非常困难,并且导致这种情况的情况对我来说是未知的,你知道为什么某些进程要摆脱我的陷阱吗?
【问题讨论】:
标签: c# process timeout .net-core