C# - 使用重定向输出

时间:2016-01-30 16:14:01

标签: c# process task

我正在尝试使用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,​​它的行为方式相同

0 个答案:

没有答案