Performance optimization of foreach loop in C#

c#, foreach, parallel-processing, performance

Solution

In C#, generic list are not thread-safe, so you can not add a items in a parallel loop.

I recommend using another class like ConcurrentBag, ConcurrentStack or ConcurrentQueue.

var pages = new ConcurrentBag<string>();
Parallel.ForEach(pageNodes, node =>
{
    try
    {
        string temp = DoSomeComplicatedModificationOnNode(node);
        if (temp.ToLower().Contains(path))
            pages.Add(node.Title);
    }
    catch (Exception)
    {
        throw;
    }
});

Remember that parallel tasks are disordered, if you want an order you will have to use an index in Parallel. List are only thead-save for reading.

System.Threading.Tasks.Parallel.For(0, pageNodes.Count, index =>
{
    string node = pageNodes[index];

    try
    {
        string temp = DoSomeComplicatedModificationOnNode(node);
        if (temp.ToLower().Contains(path))
            pages.Add(MyPage(index, node.Title));
    }
    catch (Exception)
    {
        throw;
    }
});

Problem

I've got a method: ``` IList<string> pages = new List<string>(); foreach (var node in nodes) { try { string temp = DoSomeComplicatedModificationOnNode(node); if (temp.ToLower().Contains(path)) { pages.Add(node.Title); } } catch (Exception) { continue; } } ``` DoSomeComplicatedModificationOnNode() gives exception in some cases, that's why the try{} catch block is used - I can skip the items which gives exception. The number of nodes contains several thousands of items, an item has several properties. How can I optimize this loop? I was thinking about Parallel.Foreach, but the following code gives me an error "Missing current principal": ``` IList<string> pages = new List<string>(); Parallel.ForEach(pageNodes, node => { try { string temp = DoSomeComplicatedModificationOnNode(node); if (temp.ToLower().Contains(path)) { pages.Add(node.Title); } } catch (Exception) { } }); ```

Original source