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} 已下载");
        }
相关推荐
en.en..1 分钟前
TCP/UDP 收发流程(网络字节序---函数讲解)
开发语言·php
名字还没想好☜14 分钟前
Go 用 json.Decoder 流式解析大 JSON:边读边处理不爆内存
开发语言·后端·golang·go·json
xiangyun6117 分钟前
【408数据结构 03】线性表与顺序表:C++手写SeqList
开发语言·数据结构·c++
Lsir10110_32 分钟前
从按钮“点不动“讲起——深入理解 Qt 信号槽机制
开发语言·qt·信号处理
君科程序定做34 分钟前
用 IDL 处理高分一号(GF-1 / GF-1B/C/D)数据
c语言·开发语言
敲代码的嘎仔36 分钟前
用 Redis 合并写 + DelayQueue 延迟检测,把视频播放进度写库频率降到 1/60
java·开发语言·数据库·redis·缓存·音视频·高并发
StarDream-Online1 小时前
Windows 下 uv 安装与配置完全指南(含环境变量设置)
windows·uv
代码中介商1 小时前
C++ 预约系统实战(一):项目总览与 C/S 架构设计
c语言·开发语言·c++
我叫汪枫1 小时前
RAG 进阶:切分、检索、重排序,以及它和 Agent、微调、MCP 都是什么关系
开发语言·python
弘毅 失败的 mian1 小时前
数组和指针基础
c语言·开发语言·经验分享·笔记