---
title: "Parallel.ForEach"
author: "huhu_long"
date: "2012-08-16T06:17:56Z"
tags: []
categories: ["编程语言"]
slug: "parallel-foreach"
draft: false
lastmod: "2012-09-08T03:08:26Z"
id: 1633428
url: "https://vrplat.iteye.com/blog/1633428"
---

Parallel calculation is brought in from .net 4.0 framework.
So, please be careful to avoid using un-thread-safe collections such as List<> when using Parallel calculation.

Parallel.ForEach() has multiple overrided methods for using.

Generally, below two methods are used more frequently.


```C#

System.Threading.Tasks.Parallel.ForEach<TSource>(System.Collections.Generic.IEnumerable<TSource>, System.Action<TSource>)

System.Threading.Tasks.Parallel.ForEach<TSource>(System.Collections.Generic.IEnumerable<TSource>, System.Threading.Tasks.ParallelOptions, System.Action<TSource>)

```


An example will be like this:

```C#

private List<WorkflowTask> CreateTasks(List<NetworkServiceLayerTask> ncTasks, bool returnTaskAttributes, bool checkAvailability)
        {
            List<WorkflowTask> tasks = new List<WorkflowTask>();

            if (ncTasks == null || ncTasks.Count == 0) return tasks;

            Parallel.ForEach(ncTasks, new ParallelOptions { MaxDegreeOfParallelism = 50 }, ncTask =>
            {
                WorkflowTask task = ToTask(ncTask, returnTaskAttributes, checkAvailability);

                lock(tasks) tasks.Add(task);
            });

//          tasks.AddRange(from ncTask in ncTasks.AsParallel()
//                       select ToTask(ncTask, returnTaskAttributes, checkAvailability));

            return tasks;
        }

 private WorkflowTask ToTask(NetworkServiceLayerTask ncTask, bool returnTaskAttributes, bool checkAvailability)
{
    ......
    return task;
}

```


Pls refer to <http://msdn.microsoft.com/en-us/library/dd460720.aspx> to check another MSDN example.

Also, regarding the performance among "foreach, Parallel.For, Parallel.ForEach, Linq, PLinq", please see below two articles.
<http://www.dotblogs.com.tw/asdtey/archive/2010/05/08/parallelforforeach.aspx>
<http://www.dotblogs.com.tw/asdtey/archive/2010/05/08/parallelplinq.aspx>