/// <summary> /// 下载结束后重新尝试下载失败的图片(异步) /// </summary> /// <returns>Task</returns> public static async Task ReTryAsync() { Debug.WriteLine("成功:" + "开始Retry"); List <ImageModel> failsList = new List <ImageModel>(); DownloadFailImages.ForEach(img => failsList.Add(img)); DownloadFailImages.Clear(); DelegateCommands.SetImageDownloadFailCountCommand?.Invoke(DownloadFailImages.Count()); await downloadImagesParallel(failsList); if (UnAvailablePages.Count != 0) { List <ImagePageModel> failImagePages = new List <ImagePageModel>(); UnAvailablePages.ForEach(page => failImagePages.Add(page)); UnAvailablePages.Clear(); DelegateCommands.SetUnavailableImagePageCountCommand?.Invoke(UnAvailablePages.Count()); List <ImageModel> imageModels = await getAllImageUrls(failImagePages); await downloadImagesParallel(imageModels); } SoundPlayer.PlayCompleteness(); new Window_FinishResult().Show(); }
public static async Task StartDownload(ObservableCollection <TaskItem> taskItems) { DownloadFailImages.Clear(); DownloadFinishImages.Clear(); UnAvailablePages.Clear(); for (int i = 0; i < taskItems.Count; i++) { await downloadATask(taskItems[i]); } SoundPlayer.PlayCompleteness(); new Window_FinishResult().Show(); }
/// <summary> /// 从网页中查找图片链接并下载到本地(异步) /// </summary> /// <param name="imagePageUrls">一组网页的Url</param> /// <param name="taskItem">该组网页所属的TaskItem</param> /// <returns>Task</returns> private static async Task downloadImagesParallel(List <ImageModel> imageModelList) { Object lockObj = new Object(); List <Task> taskList = new List <Task>(); var limitation = new SemaphoreSlim(ParallelTaskNum); foreach (ImageModel imageModel in imageModelList) { //ImageModel imageModelTemp = imageModel; await limitation.WaitAsync(); //把Task添加到线程池中 taskList.Add(Task.Run(async() => { try { await downloadAImageAndSave(imageModel); lock (lockObj) { imageModel.ImagePage.TaskItem.NumberOfFinish++; DownloadFinishImages.Add(imageModel); DelegateCommands.SetImageDownloadCountCommand?.Invoke(DownloadFinishImages.Count()); } } catch (Exception e) { lock (lockObj) { DownloadFailImages.Add(imageModel); DelegateCommands.SetImageDownloadFailCountCommand?.Invoke(DownloadFailImages.Count()); } } finally { limitation.Release(); } })); } //等待所有Task完成 await Task.WhenAll(taskList); }