Parallel.ForEach

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.

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:
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

你可能感兴趣的:(C#)