Мне нужно загрузить несколько файлов HTML в моем приложении ASP.NET. Средний размер файла составляет около 100 КБ.
Сейчас я использую следующий код.
foreach (var item in items)
{
string url = (string)item.Element("link");
string title = (string)item.Element("title");
string fileName = Server.MapPath(title + ".html");
// Add the attachement
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
client.DownloadFileCompleted += new AsyncCompletedEventHandler((a, b) =>
{
System.Threading.Thread.Sleep(2000);
message.Attachments.Add(new Attachment(fileName));
counter++;
// If we've downloaded all the items, send the message with the items attached to it
if (counter == totalItems)
{
SendMessage(message);
}
});
client.DownloadFileAsync(new Uri(url), fileName);
}
Как видите, я загружаю файлы асинхронно, но цикл foreach не заботится о том, что файл еще не был загружен, он переходит к следующему итерированному элементу.
В результате этого некоторые файлы не загружаются.