C# Parallel ForEach

rhinocommon

(Nicholas Rawitscher) #1

Hi guys,

I am running in to a little trouble trying to parallelise a foreach loop. I get an error at line 0, meaning that there must be something wrong in the way I am using it and is causing one of the namespaces to bug out. But I cant seem to figure out what might be wrong inisde the parallel loop. Any suggestions will be appreciated.

Here is the parallel function, and attached the gh_file

  System.Threading.Tasks.Parallel.ForEach(walkerList, (Walker w) =>
    {


    if (w.Stuck(growthList))
    {
      growthList.Add(w.Display());
    }

    else
    {

      w.Update();
      walkerLocList.Add(new GH_Point(w.Display()));
    }



    });

18_02_
25_DLA_Parallel.gh
(17.9 KB)

Thank you!

Nicholas


(qythium) #2

You can’t use regular List<T>s inside a parallel foreach loop because it is not thread-safe, take a look at concurrent types such as ConcurrentBag or SynchronizedCollection.