public async Task <AsyncDownloadResultModel> DoWork(IProgress <DownloadProgressReportModel> progressSent, CancellationToken cancellationToken) { List <FormattedTradesModel> resultData = new List <FormattedTradesModel>(); List <string[]> filteredItems = StaticMethods.GetFilteredItems(); progress = progressSent; token = cancellationToken; ItemFiltersModel filters = SqliteDataAccess.LoadItemFilters(); totalItems = filteredItems.Count; startTime = DateTimeOffset.Now.ToUnixTimeSeconds(); startedItem = 0; finishedItem = 0; maxAsync = 0; List <Task <FormattedTradesModel> > tasks = new List <Task <FormattedTradesModel> >(); while (startedItem < totalItems) { token.ThrowIfCancellationRequested(); if (maxAsync < filters.max_async_tasks) { maxAsync++; tasks.Add(Task.Run(() => downloadSite(filteredItems[startedItem]))); } Thread.Sleep(10); } FormattedTradesModel[] results = await Task.WhenAll(tasks); foreach (FormattedTradesModel model in results) { if (model.has_data) { resultData.Add(model); } } AsyncDownloadResultModel result = new AsyncDownloadResultModel(); result.item_list = resultData; result.finished_with_errors = finishedWithErrors; return(result); }
private async void btnStartWorker_Click(object sender, RoutedEventArgs e) { if (!isTaskRunning) { oldTime = DateTimeOffset.Now.ToUnixTimeSeconds(); isTaskRunning = true; pbRefresh.Value = 0; tbStatus.Text = "Step 1/2: Initializing refresh..."; btnRefresh.Content = "Cancel"; viewModel.SaveFiltersUponStart(); gridMain.IsEnabled = false; cbStations.IsEnabled = false; tbUserargoCapacity.IsEnabled = false; tbUserAvailableMoney.IsEnabled = false; ctSource = new CancellationTokenSource(); downloadWorker = new AsyncDownloadWebsites(); calculateWorker = new AsyncCalculateHauling(); progress = new Progress <DownloadProgressReportModel>(); progress.ProgressChanged += ReportProgress; try { AsyncDownloadResultModel downloadedData = await Task.Run(() => downloadWorker.DoWork(progress, ctSource.Token)); ObservableCollection <CalculateTradeModel> trades = await Task.Run(() => calculateWorker.DoWork(progress, ctSource.Token, downloadedData.item_list)); updateTable(trades); cbStations.IsEnabled = true; tbUserargoCapacity.IsEnabled = true; tbUserAvailableMoney.IsEnabled = true; pbRefresh.Value = 0; btnRefresh.Content = "Refresh data"; if (downloadedData.finished_with_errors) { tbStatus.Text = "Trades refreshed with some errors on " + DateTimeOffset.Now.ToUnixTimeSeconds().ToString(); } else { tbStatus.Text = "Trades refreshed on " + DateTimeOffset.Now.ToUnixTimeSeconds().ToString(); } } catch (OperationCanceledException) { gridMain.IsEnabled = true; btnRefresh.IsEnabled = true; cbStations.IsEnabled = true; tbUserargoCapacity.IsEnabled = true; tbUserAvailableMoney.IsEnabled = true; pbRefresh.Value = 0; btnRefresh.Content = "Refresh data"; tbStatus.Text = "Refresh cancelled. To begin, please refresh data."; } isTaskRunning = false; } else { isTaskRunning = false; btnRefresh.IsEnabled = false; ctSource.Cancel(); } }