C# 使用Parallel去执行并行下载

直接上代码:

csharp 复制代码
	//最大线程下载数量
     ParallelOptions options = new ParallelOptions
        {
            MaxDegreeOfParallelism = 5
        };
     public async Task DownloadMusicUrl(List<MusicTags> musicTags)
        {
            DateTime currentTime = DateTime.Now;
            DateTime startTime = new DateTime(1970, 1, 1);
            TimeSpan timeSpan = currentTime - startTime;
            string timestamp = ((long)timeSpan.TotalMilliseconds).ToString();
            string type = string.Empty;
            if (this.mp3.Checked) type = this.mp3.Text;
            if (this.flac.Checked) type = this.flac.Text;
            if (this.mv.Checked) type = this.mv.Text;

             并行下载URL列表中的所有文件
            List<Task> downloadTasks = new List<Task>();
            Parallel.ForEach(musicTags, options, tag =>
                {
                    Task task = Download(tag, timestamp, type);
                    downloadTasks.Add(task); // 将下载任务的 Task 添加到 downloadTasks 列表中
                    await Task.Delay(500);
                });
            await Task.WhenAll(downloadTasks C#有偿Q群:927860652); // 等待所有下载任务完成

        }

这里切记先用 Task task = Download(tag, timestamp, type);把任务添加到集合,不要直接await在ForEach的委托里面执行代码,这样会出现一些无法控制的bug,任务添加完成后,在最外面await Task.WhenAll(downloadTasks); 通过这个等待下载完成。

这样就可以很好的控制并行下载呢。

csharp 复制代码
       public async Task Download(MusicTags tag, string timestamp, string type = "mp3")
        {
            using (WebClient webClient = new WebClient())
            {
                try
                {
                    string solutionPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory))));
                    string folderPath = Path.Combine(solutionPath, "资源下载", DateTime.Now.ToString("yyyyMMdd"), timestamp);
                    gloFolderPath = folderPath;
                    Directory.CreateDirectory(folderPath);
                    string name = $"{tag.baseMusic.SongTitle}-{tag.baseMusic.Singer}.{type}";
                    // 设置下载完成后保存的本地路径和文件名
                    string localPath = Path.Combine(folderPath, name); // 替换为保存路径

                    // 订阅 DownloadProgressChanged 事件来更新进度条
                    webClient.DownloadProgressChanged += (s, args) =>
                    {
                        int progress = args.ProgressPercentage;
                        long bytesReceived = args.BytesReceived;
                        long totalBytesToReceive = args.TotalBytesToReceive;

                        UpdateProgressBar(progress, bytesReceived, totalBytesToReceive, name);
                    };

                    await webClient.DownloadFileTaskAsync(new Uri(tag.tag), localPath);

                    //Console.WriteLine("音乐下载完成,保存路径:" + localPath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("音乐下载失败:" + ex.Message + ex.StackTrace);
                }
            }

            // 下载完成后,更新进度条为 100%
            UpdateProgressBar(100, 0, 0, "下载完成");
            AppendLog($"{tag.baseMusic.SongTitle}-{tag.baseMusic.Singer} 已下载");
        }
相关推荐
傻乐u兔8 小时前
C语言进阶————指针4
c语言·开发语言
大模型玩家七七8 小时前
基于语义切分 vs 基于结构切分的实际差异
java·开发语言·数据库·安全·batch
历程里程碑8 小时前
Linux22 文件系统
linux·运维·c语言·开发语言·数据结构·c++·算法
牛奔9 小时前
Go 如何避免频繁抢占?
开发语言·后端·golang
寻星探路13 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
lly20240615 小时前
Bootstrap 警告框
开发语言
2601_9491465315 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧15 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX15 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb010315 小时前
C++课后习题训练记录Day98
开发语言·c++