【发布时间】: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