MultiThreadDownloader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. /// <summary>
  24. /// 总下载进度更新事件
  25. /// </summary>
  26. public event EventHandler TotalProgressChanged;
  27. /// <summary>
  28. /// 文件合并事件
  29. /// </summary>
  30. public event FileMergeProgressChangedEventHandler FileMergeProgressChanged;
  31. private readonly AsyncOperation _aop;
  32. #endregion
  33. #region 下载管理器
  34. public MultiThreadDownloader(string sourceUrl, string tempDir, string savePath, int numOfParts)
  35. {
  36. _url = sourceUrl;
  37. NumberOfParts = numOfParts;
  38. TempFileDirectory = tempDir;
  39. PartialDownloaderList = new List<PartialDownloader>();
  40. _aop = AsyncOperationManager.CreateOperation(null);
  41. FilePath = savePath;
  42. }
  43. public MultiThreadDownloader(string sourceUrl, string savePath, int numOfParts) : this(sourceUrl, null, savePath, numOfParts)
  44. {
  45. TempFileDirectory = Environment.GetEnvironmentVariable("temp");
  46. }
  47. public MultiThreadDownloader(string sourceUrl, int numOfParts) : this(sourceUrl, null, numOfParts)
  48. {
  49. }
  50. #endregion
  51. #region 事件
  52. private void temp_DownloadPartCompleted(object sender, EventArgs e)
  53. {
  54. WaitOrResumeAll(PartialDownloaderList, true);
  55. if (TotalBytesReceived == Size)
  56. {
  57. UpdateProgress();
  58. MergeParts();
  59. return;
  60. }
  61. OrderByRemaining(PartialDownloaderList);
  62. int rem = PartialDownloaderList[0].RemainingBytes;
  63. if (rem < 50 * 1024)
  64. {
  65. WaitOrResumeAll(PartialDownloaderList, false);
  66. return;
  67. }
  68. int from = PartialDownloaderList[0].CurrentPosition + rem / 2;
  69. int to = PartialDownloaderList[0].To;
  70. if (from > to)
  71. {
  72. WaitOrResumeAll(PartialDownloaderList, false);
  73. return;
  74. }
  75. PartialDownloaderList[0].To = from - 1;
  76. WaitOrResumeAll(PartialDownloaderList, false);
  77. PartialDownloader temp = new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), from, to, true);
  78. temp.DownloadPartCompleted += temp_DownloadPartCompleted;
  79. temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
  80. PartialDownloaderList.Add(temp);
  81. temp.Start();
  82. }
  83. void temp_DownloadPartProgressChanged(object sender, EventArgs e)
  84. {
  85. UpdateProgress();
  86. }
  87. void UpdateProgress()
  88. {
  89. int pr = (int)(TotalBytesReceived * 1d / Size * 100);
  90. if (TotalProgress != pr)
  91. {
  92. TotalProgress = pr;
  93. if (TotalProgressChanged != null)
  94. {
  95. _aop.Post(state => TotalProgressChanged(this, EventArgs.Empty), null);
  96. }
  97. }
  98. }
  99. #endregion
  100. #region 方法
  101. void CreateFirstPartitions()
  102. {
  103. Size = GetContentLength(_url, ref _rangeAllowed, ref _url);
  104. int maximumPart = (int)(Size / (25 * 1024));
  105. maximumPart = maximumPart == 0 ? 1 : maximumPart;
  106. if (!_rangeAllowed)
  107. NumberOfParts = 1;
  108. else if (NumberOfParts > maximumPart)
  109. NumberOfParts = maximumPart;
  110. for (int i = 0; i < NumberOfParts; i++)
  111. {
  112. PartialDownloader temp = CreateNewPd(i, NumberOfParts, Size);
  113. temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
  114. temp.DownloadPartCompleted += temp_DownloadPartCompleted;
  115. PartialDownloaderList.Add(temp);
  116. temp.Start();
  117. }
  118. }
  119. void MergeParts()
  120. {
  121. List<PartialDownloader> mergeOrderedList = SortPDsByFrom(PartialDownloaderList);
  122. using (var fs = new FileStream(FilePath, FileMode.Create, FileAccess.ReadWrite))
  123. {
  124. long totalBytesWritten = 0;
  125. int mergeProgress = 0;
  126. foreach (var item in mergeOrderedList)
  127. {
  128. using (FileStream pds = new FileStream(item.FullPath, FileMode.Open, FileAccess.Read))
  129. {
  130. byte[] buffer = new byte[4096];
  131. int read;
  132. while ((read = pds.Read(buffer, 0, buffer.Length)) > 0)
  133. {
  134. fs.Write(buffer, 0, read);
  135. totalBytesWritten += read;
  136. int temp = (int)(totalBytesWritten * 1d / Size * 100);
  137. if (temp != mergeProgress && FileMergeProgressChanged != null)
  138. {
  139. mergeProgress = temp;
  140. _aop.Post(state => FileMergeProgressChanged(this, temp), null);
  141. }
  142. }
  143. }
  144. File.Delete(item.FullPath);
  145. }
  146. }
  147. }
  148. PartialDownloader CreateNewPd(int order, int parts, long contentLength)
  149. {
  150. int division = (int)contentLength / parts;
  151. int remaining = (int)contentLength % parts;
  152. int start = division * order;
  153. int end = start + division - 1;
  154. end += (order == parts - 1) ? remaining : 0;
  155. return new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), start, end, true);
  156. }
  157. public static void WaitOrResumeAll(List<PartialDownloader> list, bool wait)
  158. {
  159. foreach (PartialDownloader item in list)
  160. {
  161. if (wait)
  162. item.Wait();
  163. else
  164. item.ResumeAfterWait();
  165. }
  166. }
  167. private static void BubbleSort(List<PartialDownloader> list)
  168. {
  169. bool switched = true;
  170. while (switched)
  171. {
  172. switched = false;
  173. for (int i = 0; i < list.Count - 1; i++)
  174. {
  175. if (list[i].RemainingBytes < list[i + 1].RemainingBytes)
  176. {
  177. PartialDownloader temp = list[i];
  178. list[i] = list[i + 1];
  179. list[i + 1] = temp;
  180. switched = true;
  181. }
  182. }
  183. }
  184. }
  185. //Sorts the downloader by From property to merge the parts
  186. public static List<PartialDownloader> SortPDsByFrom(List<PartialDownloader> list)
  187. {
  188. return list.OrderBy(x => x.From).ToList();
  189. }
  190. public static void OrderByRemaining(List<PartialDownloader> list)
  191. {
  192. BubbleSort(list);
  193. }
  194. public static long GetContentLength(string url, ref bool rangeAllowed, ref string redirectedUrl)
  195. {
  196. HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
  197. req.UserAgent = "Mozilla/4.0 (compatible; MSIE 11.0; Windows NT 6.2; .NET CLR 1.0.3705;)";
  198. req.ServicePoint.ConnectionLimit = 4;
  199. long ctl;
  200. using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
  201. {
  202. redirectedUrl = resp.ResponseUri.OriginalString;
  203. ctl = resp.ContentLength;
  204. rangeAllowed = resp.Headers.AllKeys.Select((v, i) => new
  205. {
  206. HeaderName = v,
  207. HeaderValue = resp.Headers[i]
  208. }).Any(k => k.HeaderName.ToLower().Contains("range") && k.HeaderValue.ToLower().Contains("byte"));
  209. resp.Close();
  210. }
  211. req.Abort();
  212. return ctl;
  213. }
  214. #endregion
  215. #region 公共方法
  216. /// <summary>
  217. /// 暂停下载
  218. /// </summary>
  219. public void Pause()
  220. {
  221. foreach (var t in PartialDownloaderList)
  222. {
  223. if (!t.Completed)
  224. t.Stop();
  225. }
  226. //Setting a Thread.Sleep ensures all downloads are stopped and exit from loop.
  227. Thread.Sleep(200);
  228. }
  229. /// <summary>
  230. /// 开始下载
  231. /// </summary>
  232. public void Start()
  233. {
  234. Task th = new Task(CreateFirstPartitions);
  235. th.Start();
  236. }
  237. /// <summary>
  238. /// 唤醒下载
  239. /// </summary>
  240. public void Resume()
  241. {
  242. int count = PartialDownloaderList.Count;
  243. for (int i = 0; i < count; i++)
  244. {
  245. if (PartialDownloaderList[i].Stopped)
  246. {
  247. int from = PartialDownloaderList[i].CurrentPosition + 1;
  248. int to = PartialDownloaderList[i].To;
  249. if (from > to) continue;
  250. PartialDownloader temp = new PartialDownloader(_url, TempFileDirectory, Guid.NewGuid().ToString(), from, to, _rangeAllowed);
  251. temp.DownloadPartProgressChanged += temp_DownloadPartProgressChanged;
  252. temp.DownloadPartCompleted += temp_DownloadPartCompleted;
  253. PartialDownloaderList.Add(temp);
  254. PartialDownloaderList[i].To = PartialDownloaderList[i].CurrentPosition;
  255. temp.Start();
  256. }
  257. }
  258. }
  259. #endregion
  260. #region 属性
  261. private string _url;
  262. private bool _rangeAllowed;
  263. #endregion
  264. #region 公共属性
  265. public bool RangeAllowed
  266. {
  267. get => _rangeAllowed;
  268. set => _rangeAllowed = value;
  269. }
  270. public string TempFileDirectory { get; set; }
  271. public string Url
  272. {
  273. get => _url;
  274. set => _url = value;
  275. }
  276. public int NumberOfParts { get; set; }
  277. public long TotalBytesReceived => PartialDownloaderList.Where(t => t != null).Sum(t => t.TotalBytesRead);
  278. public int TotalProgress { get; private set; }
  279. public long Size { get; private set; }
  280. public int TotalSpeedInBytes => PartialDownloaderList.Sum(t => t.SpeedInBytes);
  281. public List<PartialDownloader> PartialDownloaderList { get; }
  282. public string FilePath { get; set; }
  283. #endregion
  284. }
  285. }