Asynchronous downloading files in C#

六眼飞鱼酱① 提交于 2019-12-23 01:49:06

问题


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

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.

How could I do it?


回答1:


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

You should also refrain from using async void unless in an event handler




回答2:


Rather than awaiting individual tasks, create the tasks without waiting for them (stick them in a list), then await Task.WhenAll instead...

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


来源:https://stackoverflow.com/questions/26206412/asynchronous-downloading-files-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!