简体   繁体   English

C#中的异步下载文件

[英]Asynchronous downloading files in C#

I have a question about asynchronous operations in C#. 我对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");
    }
}

But this code does not really download files asynchronously. 但是这段代码并没有真正异步下载文件。 It begins to download the file from the first URL and then awaits this operation. 它开始从第一个URL下载文件,然后等待此操作。 It then begins to download the file from the second URL... and so on. 然后,它开始从第二个URL下载文件...等等。

Thereby files are downloaded one by one, and I would like to get them started downloading simultaneously. 因此,文件是一个一个地下载的,我想让它们同时开始下载。

How could I do it? 我该怎么办?

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: 您可以使用Task.WhenAll来同时await所有异步操作:

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);
}

You should also refrain from using async void unless in an event handler 除非在事件处理程序中,否则还应避免使用async void

Rather than awaiting individual tasks, create the tasks without waiting for them (stick them in a list), then await Task.WhenAll instead... 与其等待单个任务,不如不等待任务创建任务(将其粘贴在列表中),然后等待Task.WhenAll ...

public async void Download(string[] urls)
{
    //you might want to raise the connection limit, 
    //in case these are all from a single host (defaults to 6 per host)
    foreach(var url in urls)
    {
        ServicePointManager
            .FindServicePoint(new Uri(url)).ConnectionLimit = 1000;
    }
    var tasks = urls
         .Select(url =>
             DownloadHelper.DownloadAsync(
                 url,
                 @"C:\" + i.ToString() + ".mp3"))
         .ToList();
    await Task.WhenAll(tasks);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM