WaitAll with Task无法正常工作

时间:2013-03-13 11:51:29

标签: c#

我以下面的方式创建了几个任务。但似乎WaitAll无效。它无需等待即可发送响应。这里出了什么问题?

private void GetItemsPrice(IEnumerable<Item> items, int customerNumber)
    {
        try
        {
            var tasks = new List<Task>();

            for (var i = 0; i < items.Count(); i += 50)
            {
                var newTask = DoGetItemsPrice(items.Skip(i).Take(50), customerNumber);    
                tasks.Add(newTask);
            }

            Task.WaitAll(tasks.ToArray());
        }
        catch (Exception ex)
        {
            ErrorLog.WriteLog(GetType().Name, "GetItemsPrice", string.Format("customerNumber={0}", customerNumber), ex.Message);
        }
    }

private static Task DoGetItemsPrice(IEnumerable<Item> items, int customerNumber)
    {
        return Task.Factory.StartNew(() =>
        {
            var sxApiObj = new SxApiService();
            var request = new OEPricingMultipleRequest();

            request.customerNumber = customerNumber;
            request.arrayProduct =
                items.Select(
                    itemCode =>
                    new OEPricingMultipleinputProduct
                    {
                        productCode = itemCode.ItmNum,
                        quantity = itemCode.Quantity,
                        warehouse = ConfigurationVariables.DefaultWareHouse
                    }).ToArray();
            var response = sxApiObj.OEPricingMultiple(ConfigurationVariables.SfAppServer,
                                                  ConfigurationVariables.SfUserId,
                                                  ConfigurationVariables.SfPassword,
                                                  request);

            if (response.arrayPrice != null)
            {
                foreach (var priceData in response.arrayPrice)
                {
                    var productCode = priceData.productCode;
                    var item = items.FirstOrDefault(itm => itm.ItmNum == productCode);

                    if (item == null) continue;
                    item.ItmListPrice1 = priceData.price.ToString("c", ConfigurationVariables.UsCulture);
                    item.ItmListPrice2 = priceData.discountAmount.ToString("c", ConfigurationVariables.UsCulture);
                    item.ItmListPrice3 = priceData.extendedAmount.ToString("c", ConfigurationVariables.UsCulture);

                    item.Quantity = priceData.netAvailable;
                }
            }
        });
    }

1 个答案:

答案 0 :(得分:0)

我的问题没有错。 WaitAll工作正常,代码也正确。