在这种情况下,我启动一个应用程序并使用StandardOutput和StandardError读取其输出值并将其写入file.once启动该进程启动两个不同的线程,这些线程从流中读取输出并设置使用的某些字符串通过主线程将相同的内容写入outout文件。有时(非常罕见的情况)process.waitforexit()不会返回并无限期地等待。我在here处理过类似的问题,但如果我有相同的问题则无法解决问题。
以下是我的代码 -
private Thread outThread = null;
private Thread errThread = null;
private string outputText = "";
private string errorText = "";
private StreamReader outStream = null;
private StreamReader errStream = null;
protected void ReadError()
{
if (errStream != null) {
errorText = errStream.ReadToEnd();
}
}
protected void ReadOutput()
{
if (outStream != null) {
outputText = outStream.ReadToEnd();
}
}
public int launchProcess(string process, string arguments, StringDictionary env, int timeout, string logfile)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.Arguments = arguments;
psi.FileName = process;
//psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
if (env != null)
{
psi.EnvironmentVariables.Clear();
foreach (string key in env.Keys)
{
psi.EnvironmentVariables.Add(key, env[key]);
}
}
int time = (timeout == -1) ? int.MaxValue : timeout;
if (logfile != null && time != 0)
{
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.RedirectStandardInput = true;
}
try
{
Process p = Process.Start(psi);
if (time != 0)
{
if (logfile != null)
{
outStream = p.StandardOutput;
errStream = p.StandardError;
outThread = new Thread(new ThreadStart(ReadOutput));
errThread = new Thread(new ThreadStart(ReadError));
outThread.Start();
errThread.Start();
}
p.WaitForExit(time);
if (logfile != null) try
{
outThread.Join();
errThread.Join();
File.AppendAllText(logfile,
String.Format("Running '{0}' with arguments '{1}'\nStandard Output:\n", process, arguments),
Encoding.UTF8);
File.AppendAllText(logfile, outputText, Encoding.UTF8);
File.AppendAllText(logfile, "\n\nStandard Error:\n", Encoding.UTF8);
File.AppendAllText(logfile, errorText, Encoding.UTF8);
}catch (Exception e){
debugMessage("Error occurred while writing standard output to log: " + e.Message);
}
if (!p.HasExited)
{
throw new ProcessTimedOutException(psi.FileName);
}
return p.ExitCode;
}
return 0;
}
catch (Exception e)
{
debugMessage("Unable to launch process " + process + ". " + e.Message);
return -1;
}
}
请注意,在错误的情况下,只有在我手动终止进程后才返回进程,所以我猜这是一些死锁问题。任何人都可以帮我解决这个问题吗?