/// <summary> /// 重新下载失败的订单 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnFailedOrder_Click(object sender, EventArgs e) { threadCount = Convert.ToInt32(spinEditThreadCount.Value); //清空总线程量 totalThreadCount = 0; //当前交易量 currentProessNum = 0; if (failedTrade.tidList != null) { string inforMsg = string.Format("{0} {1}", DateTime.Now.ToString("HH:mm:ss"), "重新下载失败的订单!"); OrderDown.Items.Insert(0, inforMsg); /*再开线程处理*/ BackgroundWorker workerExtent = new BackgroundWorker(); workerExtent.WorkerReportsProgress = true; workerExtent.WorkerSupportsCancellation = true; workerExtent.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); workerExtent.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged); workerExtent.DoWork += new DoWorkEventHandler(worker_DoWork); /*参数传递*/ TradeTask tradeTask = new TradeTask(); tradeTask.shopNic = failedTrade.shopNick; tradeTask.ShopTradeList = failedTrade.tidList; tradeTask.sessionKey = failedTrade.sessionKey; tradeTask.totalNum = failedTrade.tidList.Count; tradeTask.threadIndex = 1; //线程开启 workerExtent.RunWorkerAsync(tradeTask); } }
/// <summary> /// Executes behavior with given context /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public override BehaviorReturnCode Behave(IBehaviorContext context) { PlayerBehaviorContext playerContext = context as PlayerBehaviorContext; if (playerContext == null) { returnCode = BehaviorReturnCode.Failure; return(returnCode); } ITradeUnit tradeUnit = playerContext.BehaviorTarget as ITradeUnit; if (tradeUnit == null) { returnCode = BehaviorReturnCode.Failure; return(returnCode); } var availRoutes = tradeUnit.Owner.GetAvailableTradeRoutes(tradeUnit, IncludeDomestic, IncludeGlobal); if (availRoutes == null || availRoutes.Count == 0) { returnCode = BehaviorReturnCode.Failure; return(returnCode); } if (tradeUnit.HasAssignedTradeRoute) { tradeUnit.CancelTrade(); } // TODO: select best trade route here BaseTradeRoute route = availRoutes[0]; route.AutoRenew = AutoRenew; route.Balance = TradeBallance; route.UpdateBalance(); TradeTask task = new TradeTask(tradeUnit, route); task.Execute(); returnCode = BehaviorReturnCode.Success; return(returnCode); }
void worker_DoWork(object sender, DoWorkEventArgs e) { TradeTask tradeTask = (TradeTask)e.Argument; int total_num = tradeTask.totalNum; string shopNick = tradeTask.shopNic; string sessionKey = tradeTask.sessionKey; List <string> tidList = tradeTask.ShopTradeList; int CurrentNum = 0; BackgroundWorker worker = (BackgroundWorker)sender; //用于记录下载失败的订单信息 failedTrade = new FailedTrade(); //买家昵称列表 List <string> buyerNickList = new List <string>(); for (int i = 0; i < tidList.Count; i++) { /*线程取消*/ if (worker.CancellationPending) { e.Cancel = true; break; } try { TradeRsp fullinfoTraderspReturn = TopService.TradeFullinfoGet(sessionKey, tidList[i]); if (fullinfoTraderspReturn == null || fullinfoTraderspReturn.Trade == null) { //加锁 lock (lockObject) { /*记录下载失败的交易*/ failedTrade.tidList.Add(tidList[i]); failedTrade.sessionKey = sessionKey; failedTrade.shopNick = shopNick; } UserState stateFail = new UserState(); stateFail.taskIndex = tradeTask.threadIndex; stateFail.tidIndex = i + 1; stateFail.tid = tidList[i]; ProcessRecord++; currentProessNum++; stateFail.message = "交易获取失败!"; /*订单下载失败*/ worker.ReportProgress(-1, stateFail);/*下载失败*/ continue; } UserState stateSuccess = new UserState(); stateSuccess.taskIndex = tradeTask.threadIndex; stateSuccess.tidIndex = i + 1; currentProessNum++; stateSuccess.tid = tidList[i]; stateSuccess.currentProessNum = (int)((currentProessNum * 100) / (float)total_num); ProcessRecord++; stateSuccess.totalProcessNum = (int)((ProcessRecord * 100) / (float)TotalProessNum); worker.ReportProgress(stateSuccess.currentProessNum, stateSuccess);/*下载成功*/ Alading.Taobao.Entity.Trade fullinfoTradersp = fullinfoTraderspReturn.Trade; if (TradeService.AddTradeOrderBuyer(fullinfoTradersp) != ReturnType.Success) { UserState SaveFailState = new UserState(); SaveFailState.shopNick = shopNick; SaveFailState.message = "保存失败!"; worker.ReportProgress(1, SaveFailState);/*参数2:表示保存失败*/ } }/*try*/ catch (System.Exception ex) { ProcessRecord++; currentProessNum++; //加锁 lock (lockObject) { /*记录下载失败的交易*/ failedTrade.tidList.Add(tidList[i]); failedTrade.sessionKey = sessionKey; failedTrade.shopNick = shopNick; } UserState exceptionState = new UserState(); exceptionState.message = ex.Message.ToString(); exceptionState.taskIndex = tradeTask.threadIndex; exceptionState.tidIndex = i + 1; exceptionState.tid = tidList[i]; worker.ReportProgress(-1, exceptionState); } }/*for 对tid遍历*/ e.Result = tradeTask.threadIndex; }
void mainWorker_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = (BackgroundWorker)sender; StringBuilder str_fail = new StringBuilder(); TradeReq tradeReq = new TradeReq(); //获取状态 tradeReq.Status = TradeStatus; //总交易量清空 TotalProessNum = 0; //错误列表清空 failedTrade = new FailedTrade(); tradeReq.PageSize = 100; //每页总数 tradeReq.PageNo = 1; //页数 /*计算总的交易量 即总进度条计算*/ for (int j = 0; j < shop_List.Count; j++) { try { #region 时间设置 /*选择近十五天*/ if (cmbSelectTime.SelectedIndex == 0) { tradeReq.StartCreated = this.dateEditBegin.DateTime.ToString("yyyy-MM-dd HH:mm:ss"); tradeReq.EndCreated = this.dateEditEnd.DateTime.ToString("yyyy-MM-dd HH:mm:ss"); } else/*开店至今*/ { tradeReq.StartCreated = shop_List[j].created.ToString("yyyy-MM-dd HH:mm:ss"); tradeReq.EndCreated = DateTime.Now.AddDays(-15).ToString("yyyy-MM-dd HH:mm:ss"); } #endregion //获取sessionkey string sessionkey = SystemHelper.GetSessionKey(shop_List[j].nick); //从淘宝上获取数据 TradeRsp tradeRsp = TopService.TradesSoldGet(sessionkey, tradeReq); //订单获取失败 if (tradeRsp != null || tradeRsp.Trades != null) { TotalProessNum += tradeRsp.TotalResults; } } catch (System.Exception ex) { BeginInvoke(new Action(() => { OrderDown.Items.Insert(0, string.Format("{0} {1}", DateTime.Now.ToString("HH:mm:ss"), ex.Message)); })); return; } } /*各个店铺的交易处理*/ for (int j = 0; j < shop_List.Count; j++) { //清空线程列表 workerList.Clear(); //清空总线程量 totalThreadCount = 0; //当前交易量 currentProessNum = 0; /*信息*/ UserState DoState = new UserState(); DoState.shopNick = shop_List[j].nick; DoState.message = "开始处理!"; mainWorker.ReportProgress(0, DoState); try { //交易列表 List <string> tidList = new List <string>(); #region 时间设置 /*选择近十五天*/ if (cmbSelectTime.SelectedIndex == 0) { tradeReq.StartCreated = this.dateEditBegin.DateTime.ToString("yyyy-MM-dd HH:mm:ss"); tradeReq.EndCreated = this.dateEditEnd.DateTime.ToString("yyyy-MM-dd HH:mm:ss"); } else/*开店至今*/ { tradeReq.StartCreated = shop_List[j].created.ToString("yyyy-MM-dd HH:mm:ss"); tradeReq.EndCreated = DateTime.Now.AddDays(-15).ToString("yyyy-MM-dd HH:mm:ss"); } #endregion //获取sessionkey string sessionkey = SystemHelper.GetSessionKey(shop_List[j].nick); //从淘宝上获取数据 TradeRsp tradeRsp = TopService.TradesSoldGet(sessionkey, tradeReq); //订单获取失败 if (tradeRsp == null || tradeRsp.Trades == null) { //异步操作 BeginInvoke(new Action(() => { OrderDown.Items.Insert(0, string.Format("{0} 网络异常,{1}店铺的订单下载失败!", DateTime.Now.ToString("HH:mm:ss"), shop_List[j].nick)); })); str_fail.Append(shop_List[j].nick); str_fail.Append(" "); continue; } if (tradeRsp != null) { foreach (Alading.Taobao.Entity.Trade tradeObj in tradeRsp.Trades.Trade) { tidList.Add(tradeObj.Tid); } /*foreach*/ } /*if*/ //店铺的总交易量 int totalResults = tradeRsp.TotalResults; BeginInvoke(new Action(() => { OrderDown.Items.Insert(0, string.Format("{0} 店铺{1}共{2}订单!", DateTime.Now.ToString("HH:mm:ss"), shop_List[j].nick, totalResults)); })); #region 计算是否需要分页获取 int PageTotalNum = 0; /*总页数*/ int PageCurrentNo = 0; /*当前页数*/ //计算总页数 PageTotalNum = (tradeRsp.TotalResults % tradeReq.PageSize == 0) ? (tradeRsp.TotalResults / tradeReq.PageSize) : (tradeRsp.TotalResults / tradeReq.PageSize + 1); /*有多余两页的订单*/ if (PageTotalNum >= 2) { for (PageCurrentNo = 2; PageCurrentNo < PageTotalNum + 1; PageCurrentNo++) { tradeReq.PageNo = PageCurrentNo; tradeRsp = TopService.TradesSoldGet(sessionkey, tradeReq); if (tradeRsp != null && tradeRsp.Trades != null) { foreach (Taobao.Entity.Trade tradeObj in tradeRsp.Trades.Trade) { if (!tidList.Contains(tradeObj.Tid)) { tidList.Add(tradeObj.Tid); } } } //if else /*获取失败*/ { if (!str_fail.ToString().Contains(shop_List[j].nick)) { str_fail.Append(shop_List[j].nick); str_fail.Append(" "); BeginInvoke(new Action(() => { OrderDown.Items.Insert(0, string.Format("{0} 网络异常,{1}店铺的订单下载失败!", DateTime.Now.ToString("HH:mm:ss"), shop_List[j].nick)); })); } break; } } //for } //if #endregion /*总交易数小于线程数*/ if (totalResults < threadCount) { threadCount = totalResults; } //每个线程交易下载量 int tradePageSize = (totalResults % threadCount == 0) ? (totalResults / threadCount) : (totalResults / threadCount + 1); #region 开启多线程 for (int i = 0; i < threadCount; i++) { //获取分给每个线程的tid列表 List <string> TradeTidList = tidList.Skip(i * tradePageSize).Take(tradePageSize).ToList(); /*线程配置*/ BackgroundWorker TradeWorker = new BackgroundWorker(); TradeWorker.WorkerReportsProgress = true; TradeWorker.WorkerSupportsCancellation = true; TradeWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); TradeWorker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged); TradeWorker.DoWork += new DoWorkEventHandler(worker_DoWork); //添加到线程列表 workerList.Add(TradeWorker); /*参数传递*/ TradeTask tradeTask = new TradeTask(); tradeTask.shopNic = shop_List[j].nick; tradeTask.ShopTradeList = TradeTidList; tradeTask.threadIndex = i + 1; tradeTask.sessionKey = sessionkey; tradeTask.totalNum = totalResults; TradeWorker.RunWorkerAsync(tradeTask); } #endregion } catch (System.Exception ex) { BeginInvoke(new Action(() => { if (ex.Message.Contains("Remote service error")) { OrderDown.Items.Insert(0, string.Format("{0} {1}", DateTime.Now.ToString("HH:mm:ss"), "不能连接远程服务器,请多尝试几次下载!".ToString())); } })); /*进度记录*/ ProcessRecord = 0; TotalProessNum = 0; TotalProessNum = 0; BeginInvoke(new Action(() => { btnDownOrders.Enabled = true; })); return; } //信号量,阻塞当前线程,这里阻塞的是下载主线程 autoReset.WaitOne(); }/*foreach 对店铺遍历*/ }