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} 已下载");
        }
相关推荐
序属秋秋秋1 小时前
《C++初阶之内存管理》【内存分布 + operator new/delete + 定位new】
开发语言·c++·笔记·学习
ruan1145142 小时前
MySQL4种隔离级别
java·开发语言·mysql
quant_19863 小时前
R语言如何接入实时行情接口
开发语言·经验分享·笔记·python·websocket·金融·r语言
百锦再7 小时前
详细解析 .NET 依赖注入的三种生命周期模式
java·开发语言·.net·di·注入·模式·依赖
风吹落叶花飘荡7 小时前
2025 Next.js项目提前编译并在服务器
服务器·开发语言·javascript
程序猿多布8 小时前
C# 值拷贝、引用拷贝、浅拷贝、深拷贝
c#
失败又激情的man8 小时前
python之requests库解析
开发语言·爬虫·python
专注VB编程开发20年8 小时前
常见 HTTP 方法的成功状态码200,204,202,201
开发语言·网络协议·tcp/ip·http
有没有没有重复的名字8 小时前
线程安全的单例模式与读者写者问题
java·开发语言·单例模式
荔枝吻8 小时前
【保姆级喂饭教程】Windows下安装Git Flow
windows·git·git flow