【问题标题】:How to organize waiting until asynchronous file download is complete?如何组织等待异步文件下载完成?
【发布时间】:2014-07-23 15:18:32
【问题描述】:

单击按钮后,我的 Silverlight 应用程序必须执行三个操作。这些行动必须连续实施。第二个动作是文件下载。我使用WebClient 类下载文件。如何组织等待文件下载完成?

void button_Click(object sender, RoutedEventArgs e) {     
  action_1(); //Some action;
  action_2(); //Downloading a file;
  //Waiting for the file to be finished downloading. How can I organize it?;
  action_3() //Another action;
}

void action_2() { 
   WebClient client = new WebClient();
   client.OpenReadCompleted += new OpenReadCompletedEventHandler(file_OpenReadCompleted);
   client.OpenReadAsync(new Uri("My uri", UriKind.Relative));
}

void file_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
  //Actions with obtained stream;
}

当然,我可以将action_3() 的调用从button_Click() 移到file_OpenReadCompleted() 函数的末尾。但我不想这样做,因为它使代码不清楚。

【问题讨论】:

  • 你使用的是哪个版本的框架?
  • 我使用 C# 4.0、MVS 2013、.NET Framework 4.5。
  • 你可以使用WebClient.OpenReadTaskAsync 来代替,这会让你await 得到结果。如果您的其他方法也是异步的,您可以再次等待这些方法。
  • 不幸的是,WebClient 的 Silverlight 版本没有 WebClient.OpenReadTaskAsync 方法。
  • 有趣 - 我不知道。不过我确实找到了this,这可能会有所帮助。

标签: c# silverlight asynchronous webclient


【解决方案1】:

我建议使用WebClient.OpenReadTaskAsync。您的代码将变为:

async void button_Click(object sender, RoutedEventArgs e) {     
    action_1(); //Some action;

    using (var wc = new WebClient()) // not sure if you can dispose at this scope 
                                     // or need to execute action_3 inside here too
    {
        var stream = await wc.OpenReadTaskAsync(new Uri("My uri", UriKind.Relative));
        .. do your thing here
    }

    action_3() //Another action;
}

【讨论】:

    猜你喜欢
    • 2014-04-03
    • 2021-01-25
    • 2020-10-04
    • 1970-01-01
    • 2019-05-31
    • 2021-11-22
    • 2020-02-22
    • 2013-02-15
    • 1970-01-01
    相关资源
    最近更新 更多