C#中的异步下载文件 [英] Asynchronous downloading files in C#

查看:302
本文介绍了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.WhenAllawait用于所有异步操作:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆