public async Task UpdatePriceToDB(IProgress <RptStructure> progress) { // using (var se = new StockEntities()) // { // // 刪除所有價格資料 // se.StockHistoricalPrice.Where(s => true).DeleteFromQuery(); // se.BulkSaveChanges(operation => operation.BatchTimeout = 200); // } var neededUpdateList = await this.GetAllNeededAddStkCode(); // 取得stkcode差集列表 var allStkPrice = await this.GetAllStkPrice(neededUpdateList, progress); // 取得所有需要新增的股票價格列表 using (var se = new StockEntities()) { // 新增所有缺少記錄的價格資料 var index = 0; RptStructure RptProgress; foreach (var priceOfList in allStkPrice) { RptProgress = new RptStructure(); await se.BulkInsertAsync(priceOfList); await se.BulkSaveChangesAsync(); RptProgress.WrittingDBProgress = (float)++index / allStkPrice.Count * 100; progress.Report(RptProgress); } RptProgress = new RptStructure() { CompletedMsg = "更新歷史價格完成!" }; progress.Report(RptProgress); } }
/// <summary> /// Gets all STK price. /// </summary> /// <param name="neededUpdateList">The needed update list.</param> /// <returns></returns> private async Task <ConcurrentStack <List <StockHistoricalPrice> > > GetAllStkPrice( List <string> neededUpdateList, IProgress <RptStructure> progress) { ConcurrentStack <List <StockHistoricalPrice> > allStkPrice = new ConcurrentStack <List <StockHistoricalPrice> >(); await Task.Run( () => { Parallel.ForEach( neededUpdateList, new ParallelOptions { MaxDegreeOfParallelism = 1 }, aStk => { var RptState = new RptStructure(); var aYahooHistoryPriceList = YahooGetHistoricalPrice( ".TW", aStk, DateTime.Now.AddYears(-20), DateTime.Now).GetAwaiter().GetResult(); if (aYahooHistoryPriceList.Count < 5) { var tryYahooCatchHistoryPriceList = YahooGetHistoricalPrice( ".TWO", aStk, DateTime.Now.AddYears(-20), DateTime.Now).GetAwaiter().GetResult(); if (tryYahooCatchHistoryPriceList.Count < 5) { // var tryGoogleCatchHistoryPriceList = GoogleGetHistoricalPrice( // "TPE/", // aStk, // DateTime.Now.AddYears(-20), // DateTime.Now).GetAwaiter().GetResult(); // if (tryGoogleCatchHistoryPriceList.Count < 5) // { // errorStkAmount++; // RptState.ErrorStkCode = $"失敗{aStk} {errorStkAmount}"; // } // else // { // allStkPrice.Push(tryGoogleCatchHistoryPriceList); // } } else { allStkPrice.Push(tryYahooCatchHistoryPriceList); } } else { allStkPrice.Push(aYahooHistoryPriceList); } RptState.UpdatePriceListsProgress = (float)allStkPrice.Count / (totalStkAmount - errorStkAmount) * 100; progress.Report(RptState); }); errorStkAmount = 0; }); return(allStkPrice); }