public async void StartDownload() { try { var taskCount = App.IsPro ? 15 : 1; var groups = Book.CatalogList.Split <BookCatalog>(taskCount); var enumerable = groups as IEnumerable <BookCatalog>[] ?? groups.ToArray(); if (groups == null || !enumerable.Any()) { return; } var tasks = new Task[enumerable.Length]; _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) }; _timer.Tick += Timer_Tick; _timer.Start(); for (var i = 0; i < enumerable.Length; i++) { if (IsDelete) { break; } tasks[i] = await Task.Factory.StartNew(async() => { var catalogs = enumerable[i]; foreach (var bookCatalog in catalogs) { try { if (IsDelete) { break; } bookCatalog.CatalogContent = await AnalisysSourceHelper.GetCatalogContent(bookCatalog.CatalogUrl); } catch (Exception e) { Console.WriteLine(e); } finally { lock (_obj) { _completedCount += 1; _progress = double.Parse(CompletedCount.ToString()) / double.Parse(TotalCount.ToString()) * 100; } } } }); } await Task.Factory.ContinueWhenAll(tasks, (obj) => { if (CompletedCount < TotalCount - 10) { if (!IsDelete) { ToastHelper.ShowMessage(Book.BookName + "下载失败", false); } ViewModelInstance.Instance.DownloadCenter.RemoveDownItem(this); return; } IsCompleted = true; InsertOrUpdateBookCatalogs(Book); DispatcherHelper.CheckBeginInvokeOnUI(() => { _timer?.Stop(); }); }); } catch (Exception e) { Console.WriteLine(e); } }
public async void StartUpdate() { try { var taskCount = 3; var groups = NeedUpdateCatalogs.Split <BookCatalog>(taskCount); var enumerable = groups as IEnumerable <BookCatalog>[] ?? groups.ToArray(); if (groups == null || !enumerable.Any()) { return; } IsUpdating = true; var tasks = new Task[enumerable.Length]; for (var i = 0; i < enumerable.Length; i++) { if (IsDeleted) { break; } tasks[i] = await Task.Factory.StartNew(async() => { var catalogs = enumerable[i]; foreach (var bookCatalog in catalogs) { try { if (IsDeleted) { break; } bookCatalog.CatalogContent = await AnalisysSourceHelper.GetCatalogContent(bookCatalog.CatalogUrl); } catch (Exception e) { Console.WriteLine(e); } finally { lock (_obj) { DispatcherHelper.CheckBeginInvokeOnUI(() => { NeedUpdateCount = (int.Parse(NeedUpdateCount) - 1).ToString(); }); } } } }); } await Task.Factory.ContinueWhenAll(tasks, (obj) => { DbHelper.AddDbOperator(new Action(() => { var reslut = DbLocalBook.InsertOrUpdateBookCatalogs(AppDataPath.GetLocalBookDbPath(), NeedUpdateCatalogs); })); DispatcherHelper.CheckBeginInvokeOnUI(() => { NeedUpdateCount = ""; }); }); } catch (Exception e) { Console.WriteLine(e); } finally { IsUpdating = false; } }