Parallel.For
Use Parallel.For to complete the execution of the parallel loop.
Parallel.For (0, index = = {Console.WriteLine ("Task ID {0}processing index: {1}", Task.currentid, Index);});
Use of Parallel.ForEach
list<string> dataList = new List<string> {"A", "BC", "CDA", "DDQF", "Eqw", "AF"};//process the elements of the collection//using a parallel foreach Loopparallel.foreach (dataList, item =>{console.writeline ("item {0} Has{1} Characters ", item, item. (Length);});
paralleloptions
You can set Maxdegreeofparallelism: The maximum number of concurrent tasks. Usage:
ParallelOptions options= New ParallelOptions () {maxdegreeofparallelism= 1}; Parallel.For (0, ten, Options, index=> {Console.WriteLine ("for index {0}started", index); Thread.Sleep (500); Console.WriteLine ("For index {0}finished", index);});
terminating a parallel loop
Parallel.For (0, ten, (int index,parallelloopstate loopstate) = {if (index%2 = = 0) {loopstate.stop ();});
You can also use Loopstate.break (). The difference is that by terminating with break (), you can get the value of Lowestbreakiteration.value and lowestbreakiteration.hasvalue externally to determine the value at the end of the loop.
You can also pass CancellationToken into the paralleloption:
ParallelOptions loopoptions =new paralleloptions () {CancellationToken = tokensource.token};try {Parallel.For (0, int64.maxvalue,loopoptions, index = = {//do something just to occupy the cpufor a littledouble result = Math.pow (index, 3)//write out the current indexconsole.writeline ("index {0},result {1}", index, result);//Put the thread to sleep, jus T toslow things downthread.sleep (100);}); catch (OperationCanceledException) {Console.WriteLine ("Caughtcancellation exception ...");
This anomaly can be captured externally to operationcanceledexception.
using TLS in a parallel loop (Thread Local Storage)
int total = 0; Parallel.For (0,101, () = 0, (int index, parallelloopstateloopstate, int tlsvalue) = {Tlsvalue + = Index;return Tlsva Lue;},value = Interlocked.add (ref total,value)); Console.WriteLine ("Total:{0}", total);//wait for input before Exitingconsole.writeline ("press ENTER Tofinish"); Console.ReadLine ();
In the above code, the process of adding from 1 to 100 is implemented in parallel.
using PLINQ
int[] SourceData = new Int[100];for (int i = 0; I <sourceData.Length; i++) {Sourcedata[i] = i;} Ienumerable<int> results =from item in Sourcedata.asparallel () where item% 2 = = 0select Item;foreach (int item in Re Sults) {Console.WriteLine ("Item{0}", Item);}
The key approach to parallel LINQ: AsParallel (). Because ToList (), ToArray (), and todictionary () are not executed, this PLINQ is executed only when the loop takes result.
Other Options
If the results are sorted after parallel execution, you can use: Sourcedata.asparallel (). AsOrdered ().
If you want to force concurrent execution to work:
Sourcedata.asparallel (). Withexecutionmode (parallelexecutionmode.forceparallelism)
If you want to limit the amount of concurrency:
Sourcedata.asparallel (). Withdegreeofparallelism (2)
Handling Exceptions and tasks is the same, catching aggregateexception exceptions externally, but be aware of the features of LINQ deferred execution to catch exceptions here in foreach:
try {foreach (double d in results) {Console.WriteLine ("Result{0}", D),} catch (AggregateException aggexception) {Aggexce Ption. Handle (Exception = {Console.WriteLine ("Handledexception of type: {0}", exception. GetType ()); return true;});
incoming CancellationToken to PLINQ
void Main () {
CancellationTokenSource tokensource= New CancellationTokenSource (); int[] SourceData = new Int[1000];for (int i = 0;i < Sourcedata.length; i++) {sourcedata[i]= i;}
Define a query that supports cancellationienumerable<double> results = Sourcedata.asparallel (). WithCancellation (Tokensource.token). Select (item=> {return Math.pow (item, 2); Thread.Sleep (200);});
Task.Factory.StartNew (() = {Thread.Sleep (+); Tokensource.cancel (); Console.WriteLine ("Token source cancelled");});
Try{//enumerate the query Resultsforeach (double D in results) {Console.WriteLine ("Result:{0}", d);}
} catch (OperationCanceledException) {Console.WriteLine ("Caught cancellation exception");}}
TPL Part5--Loops and PLINQ