Parallel.ForEach的行为和lambda表达式的参数

时间:2014-09-23 23:16:44

标签: c# parallel-processing parameter-passing

我有以下代码:

public OrderInfo GetPreviousOrder(int customerId)
{
    using (var entities = new ContosoEntities())
    {
        var previousOrder = entities.Orders
            .OrderByDescending(x => x.CreatedDate)
            .FirstOrDefault(x => x.CustomerId == customerId);

        var response = new OrderInfo
        {
            Customer = RetrieveCustomerInfo(customerId),
        };
        if (previousOrder != null)
        {
            response.FollowUps = Mapper.Map<IEnumerable<OrderFollowUp>, OrderFollowUpData[]>(previousOrder.FollowUps);
            response.Appointments = Mapper.Map<IEnumerable<Appointment>, OrderAppointment[]>(previousOrder.Appointments);
            response.DiscussionTopics = previousOrder.DiscussionTopics.Select(discussionTopic => discussionTopic.Topic).ToArray();
        }

        var actions = new Action[]
        {
            () => response.Invoices = RetriveInvoices(customerId, previousOrder),
            () => response.Items = RetrieveItems(customerId, previousOrder)
        };
        Parallel.ForEach(actions, new ParallelOptions { MaxDegreeOfParallelism = 10 }, action => action());

        return response;
    }
}

总之,此方法获取客户之前订单的信息。大多数订单信息存储在我的项目数据库中(使用实体框架访问),但是从其他来源(客户信息,发票和物品)中提取了一些信息。 有时,当RetriveInvoices方法被执行(并且客户的先前订单存储在我们的数据库中)时,传递的previousOrder变量的值为null。同样地,在其他时候,它是RetrieveItems方法获取空值而在其他时候,代码表现为(I)预期,意味着previousOrder变量实际上具有信息传递给两种方法的先前订单。两种方法都在执行,直到它们各自的最后一行,没有异常被抛出。不,两种方法都只读取previousOrder变量。

有人可以向我解释为什么我会看到这种行为吗?

0 个答案:

没有答案