teddy2 teddy2 - 11 days ago 11
C# Question

C# Parallel.ForEach, not working

I am trying to convert

ForEach
with a
Parallel.ForEach
.

ForEach
, works perfectly fine and gives the expected result. Where as when I try to use
Parallel.ForEach
, I get an error for the List variable, saying its not available.

What am I doing wrong? I have added comments in the code to explain.

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);
});


}
}
}

Answer

you syntax is incorrect use :

    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);
                 }); 
Comments