天天看點

Parallel.ForEach 方法

Parallel.ForEach 方法并行的執行ForEach,它的重載方法也很多。

http://msdn.microsoft.com/zh-cn/library/system.threading.tasks.parallel.foreach.aspx。

最簡單的是下面這個

<a href="http://msdn.microsoft.com/zh-cn/library/dd992001.aspx">ForEach&lt;TSource&gt;(IEnumerable&lt;TSource&gt;, Action&lt;TSource&gt;)</a>

一個枚舉器參數和一個Action委托。

static void Main(string[] args)

        {

            Parallel.ForEach("Hello, world", (c) =&gt;

            {

                Console.WriteLine(c.ToString());

            });

        }

Because the loop body in a parallel For or ForEach is a delegate, you can’t exit

the loop early with a break statement. Instead, you must call Break or Stop on a

ParallelLoopState object:

由于并行的For和Foreach方法的循環體是一個委托,是以不能通過break退出循環體,你隻能使用ParallelLoopState 對象的Break或者Stop方法來退出一個并行循環

For和Foreach所有的所有重載函數都接受一個Action&lt;TSource,ParallelLoopState&gt;委托,這裡可以在循環體裡使用ParallelLoopState。

 ParallelLoopState.Break()方法,:在完成目前的這輪工作之後,不再執行後繼的工作,但在目前這輪工作開始之前“已經在執行”的工作,則必須完成。

      ParallelLoopState.Stop方法時,不但不會再建立新的線程執行并行循環,而且目前“已經在執行”的工作也應該被中止 

      Stop 和 Break 的方法的差別非常微妙,需要仔細體會,可以簡單地用兩句話來表達:

n  ParallelLoopState.Stop 方法中止“目前”及“以後”的工作任務,會導緻 ParallelLoopState 對象的 IsStop 屬性值等于 true 。

n  ParallelLoopState.Break() 方法僅中止“以後”的工作任務,會導緻 ParallelLoopState 對象的 LowestBreakIteration 屬性值等于 true 。

本文轉自cnn23711151CTO部落格,原文連結:http://blog.51cto.com/cnn237111/538910 ,如需轉載請自行聯系原作者