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} 已下载");
        }
相关推荐
石像鬼₧魂石18 小时前
内网渗透靶场实操清单(基于 Vulhub+Metasploitable 2)
linux·windows·学习·ubuntu
小浣熊熊熊熊熊熊熊丶19 小时前
《Effective Java》第25条:限制源文件为单个顶级类
java·开发语言·effective java
啃火龙果的兔子19 小时前
JDK 安装配置
java·开发语言
星哥说事19 小时前
应用程序监控:Java 与 Web 应用的实践
java·开发语言
等....20 小时前
Miniconda使用
开发语言·python
zfj32120 小时前
go为什么设计成源码依赖,而不是二进制依赖
开发语言·后端·golang
醇氧20 小时前
org.jetbrains.annotations的@Nullable 学习
java·开发语言·学习·intellij-idea
Java&Develop20 小时前
Aes加密 GCM java
java·开发语言·python
weixin_4624462320 小时前
使用 Go 实现 SSE 流式推送 + 打字机效果(模拟 Coze Chat)
开发语言·后端·golang
JIngJaneIL20 小时前
基于springboot + vue古城景区管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端