我正在尝试使用Task.Run在C#中运行外部.exe并且我想捕获此应用程序的输出以处理它。这是代码:
private async void StartButton_Click(object sender, RoutedEventArgs e)
{
MyClass obj = new MyClass();
await Task.Run(() => obj.Download());
}
方法内容:
public void Download()
{
ProcessStartInfo StartInfo = new ProcessStartInfo
{
WorkingDirectory = "tools/temp/",
FileName = "tools/download.exe",
Arguments = $"{_url} {_path}",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
Process proc = new Process { StartInfo = StartInfo };
proc.OutputDataReceived += Proc_OutputDataReceived;
proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
private void Proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
// some code
}
问题是在进程完成后OutputDataReceived
事件会引发。请考虑以下事项:download.exe
下载4个文件,在每个文件后打印出文件名。如果我使用上面的代码运行它,则会下载文件,然后引发4个OutputDataReceived
事件。我希望在打印行后立即提升事件。有可能吗?
编辑:
download.exe
在新行中打印出每个文件名,如果没有Task.Run,它的行为方式相同