using System; using System.Collections; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HttpDownload { public class TaskDownloadManager { public int Capacity { get; set; } // DownloadTask list ArrayList allTasks = new ArrayList(); LimitedConcurrencyLevelTaskScheduler lcts = null; TaskFactory factory = null; /// /// /// /// 最大同时任务数[1, 30], 异常为5 public TaskDownloadManager(int count) { //ThreadPool.SetMaxThreads(count, count); if (count >= 1 && count <= 30) Capacity = count; else Capacity = 5; lcts = new LimitedConcurrencyLevelTaskScheduler(Capacity); factory = new TaskFactory(lcts); } /// /// 添加任务到队列 /// /// 文件的下载地址 /// 文件再本地的保存路径 /// 在文件中开始下载的的位置, byte /// 任务 public DownloadTask enqueueTask(string fileUrl, string fileDir, string expectedMD5, long offset = 0L) { DownloadTask task = new DownloadTask(fileUrl, fileDir, expectedMD5, offset); allTasks.Add(task); return task; } public DownloadTask enqueueTask(string taskId, string fileUrl, string fileDir, string expectedMD5, long offset = 0L) { DownloadTask task = new DownloadTask(taskId, fileUrl, fileDir, expectedMD5, offset); allTasks.Add(task); return task; } public DownloadTask getDownloadTaskByDownloadTaskId(string taskId) { foreach (DownloadTask down in allTasks) { if (taskId == down.BelongingId) { return down; } } return null; } public void runAllTasks() { foreach (DownloadTask task in allTasks) { task.resumeTask(); factory.StartNew(() => { DownloadTask.download(task); }); } } public void pauseAllTasks() { foreach (DownloadTask task in allTasks) { task.pauseTask(); } } public void resumeAllTasks() { foreach (DownloadTask task in allTasks) { task.resumeTask(); factory.StartNew(() => { DownloadTask.download(task); }); } } public ArrayList getAllTasks() { return allTasks; } public Hashtable getAllTasksMap() { Hashtable table = new Hashtable(); foreach (DownloadTask down in allTasks) { string belongingid = down.BelongingId; if (table.ContainsKey(belongingid)) { ArrayList arr = (ArrayList)table[belongingid]; arr.Add(down); } else { ArrayList arr = new ArrayList(); arr.Add(down); table.Add(belongingid, arr); } } return table; } public void runTask(DownloadTask task) { task.resumeTask(); factory.StartNew(() => { DownloadTask.download(task); }); } public void pauseTask(DownloadTask task) { task.pauseTask(); } public void resumeTask(DownloadTask task) { task.resumeTask(); factory.StartNew(() => { DownloadTask.download(task); }); } public void removeTask(DownloadTask task) { task.pauseTask(); allTasks.Remove(task); } } }