1
1

MultiThreadDownloader.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace Masuit.Tools.Net
  10. {
  11. /// <summary>
  12. /// 文件合并改变事件
  13. /// </summary>
  14. /// <param name="sender"></param>
  15. /// <param name="e"></param>
  16. public delegate void FileMergeProgressChangedEventHandler(object sender, int e);
  17. /// <summary>
  18. /// 多线程下载器
  19. /// </summary>
  20. public class MultiThreadDownloader
  21. {
  22. #region 属性
  23. private string _url;
  24. private bool _rangeAllowed;
  25. #endregion
  26. #region 公共属性
  27. /// <summary>
  28. /// RangeAllowed
  29. /// </summary>
  30. public bool RangeAllowed
  31. {
  32. get => _rangeAllowed;
  33. set => _rangeAllowed = value;
  34. }
  35. /// <summary>
  36. /// 临时文件夹
  37. /// </summary>
  38. public string TempFileDirectory { get; set; }
  39. /// <summary>
  40. /// url地址
  41. /// </summary>
  42. public string Url
  43. {
  44. get => _url;
  45. set => _url = value;
  46. }
  47. /// <summary>
  48. /// 第几部分
  49. /// </summary>
  50. public int NumberOfParts { get; set; }
  51. /// <summary>
  52. /// 已接收字节数
  53. /// </summary>
  54. public long TotalBytesReceived => PartialDownloaderList.Where(t => t != null).Sum(t => t.TotalBytesRead);
  55. /// <summary>
  56. /// 总进度
  57. /// </summary>
  58. public float TotalProgress { get; private set; }
  59. /// <summary>
  60. /// 文件大小
  61. /// </summary>
  62. public long Size { get; private set; }
  63. /// <summary>
  64. /// 下载速度
  65. /// </summary>
  66. public float TotalSpeedInBytes => PartialDownloaderList.Sum(t => t.SpeedInBytes);
  67. /// <summary>
  68. /// 下载块
  69. /// </summary>
  70. public List<PartialDownloader> PartialDownloaderList { get; }
  71. /// <summary>
  72. /// 文件路径
  73. /// </summary>
  74. public string FilePath { get; set; }
  75. #endregion
  76. #region 变量
  77. /// <summary>
  78. /// 总下载进度更新事件
  79. /// </summary>
  80. public event EventHandler TotalProgressChanged;
  81. /// <summary>
  82. /// 文件合并事件
  83. /// </summary>
  84. public event FileMergeProgressChangedEventHandler FileMergeProgressChanged;
  85. private readonly AsyncOperation _aop;
  86. #endregion
  87. #region 下载管理器
  88. /// <summary>
  89. /// 多线程下载管理器
  90. /// </summary>
  91. /// <param name="sourceUrl"></param>
  92. /// <param name="tempDir"></param>
  93. /// <param name="savePath"></param>
  94. /// <param name="numOfParts"></param>
  95. public MultiThreadDownloader(string sourceUrl, string tempDir, string savePath, int numOfParts)
  96. {
  97. _url = sourceUrl;
  98. NumberOfParts = numOfParts;
  99. TempFileDirectory = tempDir;
  100. PartialDownloaderList = new List<PartialDownloader>();
  101. _aop = AsyncOperationManager.CreateOperation(null);
  102. FilePath = savePath;
  103. }
  104. /// <summary>
  105. /// 多线程下载管理器
  106. /// </summary>
  107. /// <param name="sourceUrl"></param>
  108. /// <param name="savePath"></param>
  109. /// <param name="numOfParts"></param>
  110. public MultiThreadDownloader(string sourceUrl, string savePath, int numOfParts) : this(sourceUrl, null, savePath, numOfParts)
  111. {
  112. TempFileDirectory = Environment.GetEnvironmentVariable("temp");
  113. }
  114. /// <summary>
  115. /// 多线程下载管理器
  116. /// </summary>
  117. /// <param name="sourceUrl"></param>
  118. /// <param name="numOfParts"></param>
  119. public MultiThreadDownloader(string sourceUrl, int numOfParts) : this(sourceUrl, null, numOfParts)
  120. {
  121. }
  122. #endregion
  123. #region 事件
  124. private void temp_DownloadPartCompleted(object sender, EventArgs e)
  125. {
  126. WaitOrResumeAll(PartialDownloaderList, true);
  127. if (TotalBytesReceived == Size)
  128. {
  129. UpdateProgress();
  130. MergeParts();
  131. return;
  132. }
  133. OrderByRemaining(PartialDownloaderList);
  134. int rem = PartialDownloaderList[0].RemainingBytes;
  135. if (rem < 50 * 1024)
  136. {
  137. WaitOrResumeAll(PartialDownloaderList, false);
  138. return;
  139. }
  140. int from = PartialDownloaderList[0].CurrentPosition + rem / 2;
  141. int to = PartialDownloaderList[0].To;
  142. if (from > to)
  143. {
  144. WaitOrResumeAll(PartialDownloaderList, false);
  145. return;
  146. }
  147. PartialDownloaderList[0].To = from - 1;
  148. WaitOrResumeAll(PartialDownloaderList, false);
  149. PartialDownloader temp = new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), from, to, true);
  150. temp.DownloadPartCompleted += temp_DownloadPartCompleted;
  151. temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
  152. PartialDownloaderList.Add(temp);
  153. temp.Start();
  154. }
  155. void temp_DownloadPartProgressChanged(object sender, EventArgs e)
  156. {
  157. UpdateProgress();
  158. }
  159. void UpdateProgress()
  160. {
  161. int pr = (int)(TotalBytesReceived * 1d / Size * 100);
  162. if (TotalProgress != pr)
  163. {
  164. TotalProgress = pr;
  165. if (TotalProgressChanged != null)
  166. {
  167. _aop.Post(state => TotalProgressChanged(this, EventArgs.Empty), null);
  168. }
  169. }
  170. }
  171. #endregion
  172. #region 方法
  173. void CreateFirstPartitions()
  174. {
  175. Size = GetContentLength(_url, ref _rangeAllowed, ref _url);
  176. int maximumPart = (int)(Size / (25 * 1024));
  177. maximumPart = maximumPart == 0 ? 1 : maximumPart;
  178. if (!_rangeAllowed)
  179. NumberOfParts = 1;
  180. else if (NumberOfParts > maximumPart)
  181. NumberOfParts = maximumPart;
  182. for (int i = 0; i < NumberOfParts; i++)
  183. {
  184. PartialDownloader temp = CreateNewPd(i, NumberOfParts, Size);
  185. temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
  186. temp.DownloadPartCompleted += temp_DownloadPartCompleted;
  187. PartialDownloaderList.Add(temp);
  188. temp.Start();
  189. }
  190. }
  191. void MergeParts()
  192. {
  193. List<PartialDownloader> mergeOrderedList = SortPDsByFrom(PartialDownloaderList);
  194. using (var fs = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))
  195. {
  196. long totalBytesWritten = 0;
  197. int mergeProgress = 0;
  198. foreach (var item in mergeOrderedList)
  199. {
  200. using (FileStream pds = new FileStream(item.FullPath, FileMode.Open, FileAccess.Read))
  201. {
  202. byte[] buffer = new byte[4096];
  203. int read;
  204. while ((read = pds.Read(buffer, 0, buffer.Length)) > 0)
  205. {
  206. fs.Write(buffer, 0, read);
  207. totalBytesWritten += read;
  208. int temp = (int)(totalBytesWritten * 1d / Size * 100);
  209. if (temp != mergeProgress && FileMergeProgressChanged != null)
  210. {
  211. mergeProgress = temp;
  212. _aop.Post(state => FileMergeProgressChanged(this, temp), null);
  213. }
  214. }
  215. }
  216. File.Delete(item.FullPath);
  217. }
  218. }
  219. }
  220. PartialDownloader CreateNewPd(int order, int parts, long contentLength)
  221. {
  222. int division = (int)contentLength / parts;
  223. int remaining = (int)contentLength % parts;
  224. int start = division * order;
  225. int end = start + division - 1;
  226. end += (order == parts - 1) ? remaining : 0;
  227. return new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), start, end, true);
  228. }
  229. /// <summary>
  230. /// 暂停或继续
  231. /// </summary>
  232. /// <param name="list"></param>
  233. /// <param name="wait"></param>
  234. public static void WaitOrResumeAll(List<PartialDownloader> list, bool wait)
  235. {
  236. foreach (PartialDownloader item in list)
  237. {
  238. if (wait)
  239. item.Wait();
  240. else
  241. item.ResumeAfterWait();
  242. }
  243. }
  244. /// <summary>
  245. /// 冒泡排序
  246. /// </summary>
  247. /// <param name="list"></param>
  248. private static void BubbleSort(List<PartialDownloader> list)
  249. {
  250. bool switched = true;
  251. while (switched)
  252. {
  253. switched = false;
  254. for (int i = 0; i < list.Count - 1; i++)
  255. {
  256. if (list[i].RemainingBytes < list[i + 1].RemainingBytes)
  257. {
  258. PartialDownloader temp = list[i];
  259. list[i] = list[i + 1];
  260. list[i + 1] = temp;
  261. switched = true;
  262. }
  263. }
  264. }
  265. }
  266. /// <summary>
  267. /// Sorts the downloader by From property to merge the parts
  268. /// </summary>
  269. /// <param name="list"></param>
  270. /// <returns></returns>
  271. public static List<PartialDownloader> SortPDsByFrom(List<PartialDownloader> list)
  272. {
  273. return list.OrderBy(x => x.From).ToList();
  274. }
  275. /// <summary>
  276. /// 按剩余时间排序
  277. /// </summary>
  278. /// <param name="list"></param>
  279. public static void OrderByRemaining(List<PartialDownloader> list)
  280. {
  281. BubbleSort(list);
  282. }
  283. /// <summary>
  284. /// 获取内容长度
  285. /// </summary>
  286. /// <param name="url"></param>
  287. /// <param name="rangeAllowed"></param>
  288. /// <param name="redirectedUrl"></param>
  289. /// <returns></returns>
  290. public static long GetContentLength(string url, ref bool rangeAllowed, ref string redirectedUrl)
  291. {
  292. HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
  293. req.UserAgent = "Mozilla/4.0 (compatible; MSIE 11.0; Windows NT 6.2; .NET CLR 1.0.3705;)";
  294. req.ServicePoint.ConnectionLimit = 4;
  295. long ctl;
  296. using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
  297. {
  298. redirectedUrl = resp.ResponseUri.OriginalString;
  299. ctl = resp.ContentLength;
  300. rangeAllowed = resp.Headers.AllKeys.Select((v, i) => new
  301. {
  302. HeaderName = v,
  303. HeaderValue = resp.Headers[i]
  304. }).Any(k => k.HeaderName.ToLower().Contains("range") && k.HeaderValue.ToLower().Contains("byte"));
  305. resp.Close();
  306. }
  307. req.Abort();
  308. return ctl;
  309. }
  310. #endregion
  311. #region 公共方法
  312. /// <summary>
  313. /// 暂停下载
  314. /// </summary>
  315. public void Pause()
  316. {
  317. foreach (var t in PartialDownloaderList)
  318. {
  319. if (!t.Completed)
  320. t.Stop();
  321. }
  322. //Setting a Thread.Sleep ensures all downloads are stopped and exit from loop.
  323. Thread.Sleep(200);
  324. }
  325. /// <summary>
  326. /// 开始下载
  327. /// </summary>
  328. public void Start()
  329. {
  330. Task th = new Task(CreateFirstPartitions);
  331. th.Start();
  332. }
  333. /// <summary>
  334. /// 唤醒下载
  335. /// </summary>
  336. public void Resume()
  337. {
  338. int count = PartialDownloaderList.Count;
  339. for (int i = 0; i < count; i++)
  340. {
  341. if (PartialDownloaderList[i].Stopped)
  342. {
  343. int from = PartialDownloaderList[i].CurrentPosition + 1;
  344. int to = PartialDownloaderList[i].To;
  345. if (from > to) continue;
  346. PartialDownloader temp = new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), from, to, _rangeAllowed);
  347. temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
  348. temp.DownloadPartCompleted += temp_DownloadPartCompleted;
  349. PartialDownloaderList.Add(temp);
  350. PartialDownloaderList[i].To = PartialDownloaderList[i].CurrentPosition;
  351. temp.Start();
  352. }
  353. }
  354. }
  355. #endregion
  356. }
  357. }