C#Parallel.ForEach,不工作

时间:2016-11-21 21:48:09

标签: c# parallel.foreach

我正在尝试将ForEach转换为Parallel.ForEach

ForEach,完美无缺,并给出了预期的结果。当我尝试使用Parallel.ForEach时,我得到List变量的错误,说它不可用。

我做错了什么?我在代码中添加了注释来解释。

 public  class CalssTest
    {

        List<AssetDetails> assets;
        AssetDetails asset;


        private void loadData()
        {
           //Loading Assetdetails here
            //Skipped here to keep the code short. 
        }

        private void cmdValidate_Click(object sender, RoutedEventArgs e)
        {
             OrderManager om = new OrderManager();

             using (ATXFunctions atx = new ATXFunctions())
             {
                 //*****THIS WORKS *********//.
                foreach (AssetDetails ad in assets)
                {
                    ad.OrderEntry.OrderType= "A";
                    ad.OrderEntry.Portfolio = "John";
                    ad.OrderEntry.Quantity = 1000;                    
                    ad.Compliance.Result = om.RunCompliance(atx.AtxEngine, ad.StockEntry, ad.OrderEntry);              
                }

                  //*****THIS ERRORS OUT *********//.
                 // Error ::
                 //The name 'assets' does not exist in the current context

                 Parallel.ForEach (assets (ad) =>
                 {
                     ad.OrderEntry.OrderType = "A";
                     ad.OrderEntry.Customer = "John";
                     ad.OrderEntry.Quantity = 1000;
                     ad.Compliance.Result = om.ValidateOrder(ad.StockEntry, ad.OrderEntry);
                 });


             }
        }
    }

1 个答案:

答案 0 :(得分:4)

你的语法不正确使用:

    Parallel.ForEach(assets , (ad) =>
    {
                     ad.OrderEntry.OrderType = "A";
                     ad.OrderEntry.Customer = "John";
                     ad.OrderEntry.Quantity = 1000;
                     ad.Compliance.Result = om.ValidateOrder(ad.StockEntry, ad.OrderEntry);
                 });