下列寫法是,開兩條 thread 平行處理,可以節省約一半時間
public ConcurrentBag<V2SalesOrderGetDataList> ConcurencyGetApp91OrderDetails(List<string> TMCodes, int shopId, ref ConcurrentBag<string> orderErrMsgs)
{
#region 平行查詢
ConcurrentBag<V2SalesOrderGetDataList> result = new ConcurrentBag<V2SalesOrderGetDataList>();
ConcurrentBag<string> errs = new ConcurrentBag<string>();
ConcurrentQueue<string> TMCodeQueues = new ConcurrentQueue<string>();
TMCodes.ForEach(x => TMCodeQueues.Enqueue(x));
Action searchOrderDetail = () =>
{
if (!TMCodeQueues.IsEmpty)
{
string TMCode = string.Empty;
while (TMCodeQueues.TryDequeue(out TMCode))
{
V2SalesOrderGetReqModel reqModel = new V2SalesOrderGetReqModel()
{
ShopId = shopId,
TGCode = null,
TMCode = TMCode,
TSCode = null,
};
try
{
V2SalesOrderGet91API req = new V2SalesOrderGet91API();
var resp = req.Execute(reqModel, shopId);
if (resp.Status == "Success")
{
foreach (var l in resp.Data.List)
{
result.Add(l);
}
}
else
{
//主單編號 , 錯誤原因
errs.Add(TMCode + " , " + resp.ErrorMessage);
}
}
catch (Exception ex)
{
errs.Add(TMCode + " , " + ex.Message);
}
}
}
};
//指派Thread
Parallel.Invoke(searchOrderDetail, searchOrderDetail);
#endregion
//查詢失敗
orderErrMsgs = errs;
return result;
}