当前位置: 首页 > news >正文

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

直接上代码:

	//最大线程下载数量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); 通过这个等待下载完成。
这样就可以很好的控制并行下载呢。

       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} 已下载");}
http://www.lryc.cn/news/192617.html

相关文章:

  • @Component 和 @Bean的区别
  • 百度测试开发工程师面试心得
  • 发现更多美景!XnViewMP for Mac/Windows 图片浏览软件
  • 城市广告牌安全传感器特点有哪些?
  • 源码部署lamt架构
  • 【Java 进阶篇】JavaScript Math对象详解
  • geecg-uniapp 路由修改 页面创建 (2)
  • 微信开发者工具下载
  • ctfshow萌新计划web9-14(正则匹配绕过)
  • 【数据结构】单链表按位序插入元素e【前插】(带头结点的和不带头结点的)这篇很重要,文字说明比起其他篇是正确的
  • Maven Surefire Exclude 无效问题排查日志
  • ArcGIS笔记4_水动力模型验证不理想时如何修改局部水深地形
  • 介绍一下mysql有哪些索引类型
  • #力扣:125. 验证回文串@FDDLC
  • 分享一下便利店怎么做微信小程序
  • Gitlab CI/CD 入门教程
  • 【mfc/VS2022】计图实验:绘图工具设计知识笔记
  • C# PortraitModeFilter (人物图片)背景模糊
  • centos7下安装elasticsearch7.8.1并配置远程连接
  • MongoDB的作用和安装方法
  • spring boot 使用SSE向前端推送数据
  • C++智能指针(三)——unique_ptr初探
  • Composition Api 与 Options Api 有什么区别?
  • 紫光同创FPGA实现UDP协议栈网络视频传输,基于YT8511和RTL8211,提供4套PDS工程源码和技术支持
  • 深度学习简述
  • 【从零开始学习Redis | 第二篇】Redis中的数据类型和相关命令
  • 数据结构 - 3(链表12000字详解)
  • Jmeter性能测试插件jpgc的安装
  • 关于safari浏览器浏览html video标签无法正常播放的问题
  • 【C++代码】最大二叉树,合并二叉树,二叉搜索树中的搜索,验证二叉搜索树--代码随想录