我正在下載100K +個文件,並希望在補丁程序中執行此操作,例如一次執行100個文件。在for循環中每x次運行一次異步
static void Main(string[] args) {
Task.WaitAll(
new Task[]{
RunAsync()
});
}
// each group has 100 attachments.
static async Task RunAsync() {
foreach (var group in groups) {
var tasks = new List<Task>();
foreach (var attachment in group.attachments) {
tasks.Add(DownloadFileAsync(attachment, downloadPath));
}
await Task.WhenAll(tasks);
}
}
static async Task DownloadFileAsync(Attachment attachment, string path) {
using (var client = new HttpClient()) {
using (var fileStream = File.Create(path + attachment.FileName)) {
var downloadedFileStream = await client.GetStreamAsync(attachment.url);
await downloadedFileStream.CopyToAsync(fileStream);
}
}
}
預計 希望滿月下載100個文件的時間,然後下載下一個100;
實際 它在同一時間下載更多。快速出錯Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host
這是它得到了標記爲重複一個恥辱,因爲其他問題使用顯著不同的方法,我很樂意去學習爲什麼用昆汀使用的一個失敗。 – Bartosz
我同意;不是重複的。我的猜測是HttpClient方法會比你期望的更早返回。 – BradleyDotNET
我強烈推薦閱讀[.net 4.5的異步HttpClient是密集加載應用程序的不好選擇嗎?](https://stackoverflow.com/questions/16194054/is-async-httpclient-from-net-4-5-a -bad選換密集型負載的應用程序)。 –