Приложение 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()
. Но я не хочу этого делать, потому что это делает код неясным.
Я бы рекомендовал использовать 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;
}