如何组织等待异步文件下载完成?

时间:2014-07-23 15:18:33

标签: c# silverlight asynchronous webclient

我的Silverlight应用程序必须在单击Button后执行三个操作。必须连续实施这些行动。第二个动作是文件下载。我使用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()功能的结尾。但我不想这样做,因为它使代码不清楚。

1 个答案:

答案 0 :(得分: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;
}