我正在编写一个创建Process并运行它的函数。
这是原始功能:
public static void LaunchApplication(string runCommand, string commandArguments, string workingDir, string informMessage)
{
try
{
Process applicationProcess = new Process();
applicationProcess.StartInfo.FileName = runCommand;
applicationProcess.StartInfo.WorkingDirectory = workingDir;
applicationProcess.StartInfo.Arguments = commandArguments;
applicationProcess.StartInfo.UseShellExecute = false;
WriteHeadlineToConsole(informMessage);
applicationProcess.Start();
while (Process.GetProcesses().Any(runningProcess => runningProcess.Id == applicationProcess.Id)) { }
WriteHeadlineToConsole("Finished " + informMessage);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
}
我想将函数的签名更改为:
public static void LaunchApplication(string runCommand, string commandArguments, string workingDir, string informMessage, Func<object, DataReceivedEventArgs> myMethodName)
然后在函数内部重定向输出,如:
applicationProcess.OutputDataReceived += new DataReceivedEventHandler(myMethodName);
可以这样做吗?
答案 0 :(得分:0)
试试这个:
public static void LaunchApplication(string runCommand, string commandArguments, string workingDir, string informMessage, Action<string> redirectOutput, Action<string> redirectError)
{
try
{
Process applicationProcess = new Process();
applicationProcess.StartInfo.FileName = runCommand;
applicationProcess.StartInfo.WorkingDirectory = workingDir;
applicationProcess.StartInfo.Arguments = commandArguments;
applicationProcess.StartInfo.UseShellExecute = false;
applicationProcess.EnableRaisingEvents = true;
applicationProcess.StartInfo.CreateNoWindow = true;
if (redirectOutput != null)
applicationProcess.OutputDataReceived += (s, data) => redirectOutput(data.Data);
if (redirectError != null)
applicationProcess.ErrorDataReceived += (sErr, errData) => redirectError(errData.Data);
GeneralUtils.WriteHeadlineToConsole(informMessage);
applicationProcess.Start();
if (redirectOutput != null)
applicationProcess.BeginOutputReadLine();
if (redirectError != null)
applicationProcess.BeginErrorReadLine();
applicationProcess.WaitForExit();
GeneralUtils.WriteHeadlineToConsole("Finished " + informMessage);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
}
用法:
LaunchApplication("cmd.exe", "/C ipconfig /all", "C:\\Windows", "Test",
s => Console.WriteLine("HELLO: " + s));
<强> PS 强>:
以下代码很糟糕!可能会抛出AccessDeniedException
,CPU会变得疯狂!
while (Process.GetProcesses().Any(runningProcess => runningProcess.Id == applicationProcess.Id)) { }
改为使用applicationProcess.WaitForExit();
!