C#中的异步下载文件 [英] Asynchronous downloading files in C#
问题描述
我对C#中的异步操作有疑问.假设我有一些像这样的代码:
I have a question about asynchronous operations in C#. Suppose I have some code like this:
public async void Download(string[] urls)
{
for(int i = 0; i < urls.Length; i++);
{
await DownloadHelper.DownloadAsync(urls[i], @"C:\" + i.ToString() + ".mp3");
}
}
但是此代码并没有真正异步下载文件.它开始从第一个URL下载文件,然后等待此操作.然后,它开始从第二个URL下载文件...等等.
But this code does not really download files asynchronously. It begins to download the file from the first URL and then awaits this operation. It then begins to download the file from the second URL... and so on.
因此,文件是一个一个地下载的,我想让它们同时开始下载.
Thereby files are downloaded one by one, and I would like to get them started downloading simultaneously.
我该怎么办?
推荐答案
当您说异步时,是指并发,它们并不相同.您可以同时将Task.WhenAll
至await
用于所有异步操作:
When you say asynchronous you mean concurrent, these are not the same. You can use Task.WhenAll
to await
for all asynchronous operations at the same time:
public async Task Download(string[] urls)
{
var tasks = new List<Task>();
for(int i = 0; i < urls.Length; i++);
{
tasks.Add(DownloadHelper.DownloadAsync(urls[i], @"C:\" + i.ToString() + ".mp3"));
}
await Task.WhenAll(tasks);
}
除非在事件处理程序中使用,否则还应避免使用async void
You should also refrain from using async void
unless in an event handler
这篇关于C#中的异步下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!