在以下例子中,使用ForEach计算多个Order的总体价格。在ForEach方法中,首先把参数初始化为0f,然后用把同一个Order
的多个OrderItem价格进行累加,计算出Order的价格,最后把多个Order的价格进行累加,计算出多个Order的总体价格。
public class Order
{
public int ID;
public float Price;
}
public class OrderItem
{
public int ID;
public string Goods;
public int OrderID;
public float Price;
public int Count;
}
class Program
{
static void Main(string[] args)
{
//设置最大线程数
ThreadPool.SetMaxThreads(1000, 1000);
float totalPrice = 0f;
//并行查询
var parallelResult = Parallel.ForEach(GetOrderList(),
() => 0f, //把参数初始值设为0
(order, state, orderPrice) =>
{
//计算单个Order的价格
orderPrice = GetOrderItem().Where(item => item.OrderID == order.ID)
.Sum(item => item.Price * item.Count);
order.Price = orderPrice;
ThreadPoolMessage(order);
return orderPrice;
},
(finallyPrice) =>
{
totalPrice += finallyPrice;//计算多个Order的总体价格
}
);
while (!parallelResult.IsCompleted)
Console.WriteLine("Doing Work!");
Console.WriteLine("Total Price is:" + totalPrice);
Console.ReadKey();
}
//虚拟数据
static IList<Order> GetOrderList()
{
IList<Order> orderList = new List<Order>();
Order order1 = new Order();
order1.ID = 1;
orderList.Add(order1);
............
return orderList;
}
//虚拟数据
static IList<OrderItem> GetOrderItem()
{
IList<OrderItem> itemList = new List<OrderItem>();
OrderItem orderItem1 = new OrderItem();
orderItem1.ID = 1;
orderItem1.Goods = "iPhone 4S";
orderItem1.Price = 6700;
orderItem1.Count = 2;