DownloadFileTaskAsync一次只下载2个文件

时间:2016-05-17 10:57:15

标签: .net

我已经实现了以下线程中的代码,但是我发现所有文件都开始下载,但一次只下载2个文件

Asynchronously and parallelly downloading files

private static async Task<Tuple<string, string, Exception>> DownloadFileTaskAsync(string remotePath, string localPath = null, int timeOut = 3000)
        {
            try
            {

                localPath = localPath + remotePath.Split('/')[5].ToString();

                using (var client = new WebClient())
                {
                    client.Credentials = new NetworkCredential("user", "password");

                    using (var timer = new Timer(timerCallback, client, timeOut, Timeout.Infinite))
                    {
                        await client.DownloadFileTaskAsync(remotePath, localPath);
                    }
                    Debug.WriteLine(string.Format("DownloadFileTaskAsync (downloaded): {0}", remotePath));
                    return new Tuple<string, string, Exception>(remotePath, localPath, null);
                }
            }
            catch (Exception ex)
            {
                return new Tuple<string, string, Exception>(remotePath, null, ex);
            }
        }


        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            IEnumerable<string> enumerable = new string[] {"https://somepath.com/file1.zip" };
            var results = new List<Tuple<string, string, Exception>>();
            await enumerable.ForEachAsync(s => DownloadFileTaskAsync(s, "C:\\Download\\", 10000), (url, t) => results.Add(t));

        }

    }

    public static class Extensions
    {
        public static Task ForEachAsync<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, Task<TResult>> taskSelector, Action<TSource, TResult> resultProcessor)
        {
            var oneAtATime = new SemaphoreSlim(5, 10);
            return Task.WhenAll(
                from item in source
                select ProcessAsync(item, taskSelector, resultProcessor, oneAtATime));
        }

        private static async Task ProcessAsync<TSource, TResult>(TSource item, Func<TSource, Task<TResult>> taskSelector, Action<TSource, TResult> resultProcessor, SemaphoreSlim oneAtATime)
        {
            TResult result = await taskSelector(item);
            await oneAtATime.WaitAsync();
            try
            {
                resultProcessor(item, result);
            }
            finally
            {
                oneAtATime.Release();
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

这是因为2是ServicePointManager允许的默认并发连接数。

解决方案很简单:

System.Net.ServicePointManager.DefaultConnectionLimit = 10; // Whatever you want it to be