/// <summary> /// download file with Multiple-threaded, resume-from-break /// </summary> /// <param name="url"></param> /// <param name="filePath"></param> /// <param name="totalSize"></param> /// <param name="func"></param> /// <returns></returns> private bool RangeDownload(string url, string filePath, long totalSize, Func <long, long, bool> func) { if (!FileUtil.EnsureFileSize(filePath, totalSize)) { return(false); } const int threadCount = 5; long length = totalSize / threadCount; var workers = new List <RangeDownloadWorker>(); long readSize = 0; for (int i = 0; i < threadCount; ++i) { long start = i * length; long end = (i + 1 == threadCount) ? (totalSize - 1) : (start + length); var worker = new RangeDownloadWorker(url, filePath, start, end, count => { if (func == null) { return(true); } lock (func) { readSize += count; func(readSize, totalSize); } return(true); }); workers.Add(worker); if (!worker.Start()) { break; } } bool result = true; for (int i = 0; i < workers.Count; ++i) { if (!result) { workers[i].Stop(); } result = workers[i].Join(); } return(true); }
/// <summary> /// download file with Multiple-threaded, resume-from-break /// </summary> /// <param name="url"></param> /// <param name="filePath"></param> /// <param name="totalSize"></param> /// <param name="func"></param> /// <returns></returns> private bool RangeDownload(string url, string filePath, long totalSize, Func<long, long, bool> func) { if (!FileUtil.EnsureFileSize(filePath, totalSize)) return false; const int threadCount = 5; long length = totalSize/threadCount; var workers = new List<RangeDownloadWorker>(); long readSize = 0; for (int i = 0; i < threadCount; ++i) { long start = i*length; long end = (i + 1 == threadCount) ? (totalSize - 1) : (start + length); var worker = new RangeDownloadWorker(url, filePath, start, end, count => { if (func == null) return true; lock (func) { readSize += count; func(readSize, totalSize); } return true; }); workers.Add(worker); if (!worker.Start()) break; } bool result = true; for (int i = 0; i < workers.Count; ++i) { if (!result) { workers[i].Stop(); } result = workers[i].Join(); } return true; }