如何从采用IProgress <t>参数的异步方法中取得进展?

时间:2016-04-17 17:19:35

标签: c# download

我正在尝试使用C#下载mega.nz上托管的文件。我正在使用MegaApiClient,但我无法理解如何通过此功能获得下载进度:

public Task DownloadFileAsync(Uri uri, string outputFile, IProgress<double> progress)
{
  return Task.Run((Action) (() =>
  {
    if (string.IsNullOrEmpty(outputFile))
      throw new ArgumentNullException("outputFile");
    using (Stream stream = (Stream) new ProgressionStream(this.Download(uri), progress))
      this.SaveStream(stream, outputFile);
  }));
}

到目前为止我所拥有的:

var client = new MegaApiClient();
        client.LoginAnonymous();
        IProgress<double> ze = null;
        client.DownloadFileAsync(new Uri("https://mega.nz/#!Yo0l2YiQ!hW7Hzqrjlm3-zO31oof_dQ6Wd23YsIT5ZI8v-9Fau2s"), Directory.GetCurrentDirectory() + "\\ze.rar", ze);

如何检索进度?

1 个答案:

答案 0 :(得分:0)

您需要创建并传入Progress<T>,而不是null。最终传入的Progress<T>由异步方法调用,以向您报告进度。

将进度输出到控制台的单行更改

Progress<double> ze = new Progress<double>(p => Console.WriteLine($"Progress updated: {p}"); 
client.DownloadFileAsync(new Uri("https://mega.nz/#!Yo0l2YiQ!hW7Hzqrjlm3-zO31oof_dQ6Wd23YsIT5ZI8v-9Fau2s"), Directory.GetCurrentDirectory() + "\\ze.rar", ze);

您也可以听取Progress<T>.ProgressChanged事件的相同效果。