我将执行一个进程 (lame.exe) 将 WAV 文件编码为 MP3。
我想处理进程的STDOUT和STDERR来显示进度信息。
我需要使用线程吗?我无法理解它。
一些简单的示例代码将不胜感激。
谢谢
If running via the Process
class, you can redirect the streams so you may process them. You can read from stdout or stderr synchronously or asynchronously. To enable redirecting, set the appropriate redirection properties to true
for the streams you want to redirect (e.g., RedirectStandardOutput
) and set UseShellExecute
to false
. Then you can just start the process and read from the streams. You can also feed input redirecting stdin.
e.g., Process and print whatever the process writes to stdout synchronously
var proc = new Process()
{
StartInfo = new ProcessStartInfo(@"SomeProcess.exe")
{
RedirectStandardOutput = true,
UseShellExecute = false,
}
};
if (!proc.Start())
{
// handle error
}
var stdout = proc.StandardOutput;
string line;
while ((line = stdout.ReadLine()) != null)
{
// process and print
Process(line);
Console.WriteLine(line);
}
有一个 MSDN 示例...这是一个简化版本:
var StdOut = "";
var StdErr = "";
var stdout = new StringBuilder();
var stderr = new StringBuilder();
var psi = new ProcessStartInfo();
psi.FileName = @"something.exe";
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
var proc = new Process();
proc.StartInfo = psi;
proc.OutputDataReceived += (sender, e) => { stdout.AppendLine(e.Data); };
proc.ErrorDataReceived += (sender, e) => { stderr.AppendLine(e.Data); };
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit(10000); // per sachin-joseph's comment
StdOut = stdout.ToString();
StdErr = stderr.ToString();
您应该能够通过事件收听 STDOUT Process.OutputDataReceived
。MSDN 页面上有一个示例。STDERR还有一个Process.ErrorDataReceived
活动。