Parallel class
The parallel class is a good abstraction for threads. This class is located in the System.Threading.Tasks namespace and provides data and task parallelism.
1. Cycle with the Parallel.For () method
////Simple ScenarioParallelloopresult result =Parallel.For (0,Ten,Asynci ={Console.WriteLine ("{0}, Task: {1}, Thread: {2}", I, Task.currentid, Thread.CurrentThread.ManagedThreadId); awaitTask.delay (Ten); Console.WriteLine ("{0}, Task: {1}, Thread: {2}", I, Task.currentid, Thread.CurrentThread.ManagedThreadId); }); Console.WriteLine ("Is completed: {0}", result. iscompleted);
2. Stop Parallel.For Early
An overloaded version of the for () method accepts parameters of the third action<int, parallelloopstate> type. Using these parameters to define a method, you can call the ParallelLoopState break () or stop () method to affect the loop result.
//Breaking earlyParallelloopresult result =Parallel.For (Ten, +, (intI, parallelloopstate pls) ={Console.WriteLine ("I: {0} task {1}", I, Task.currentid); Thread.Sleep (Ten); if(I > the) pls. Break (); }); Console.WriteLine ("Is completed: {0}", result. iscompleted); if(!result. iscompleted) Console.WriteLine ("Lowest break iteration: {0}", result. Lowestbreakiteration);
3. Use the Parallel.ForEach () method to cycle
string[] data = {"Zero"," One"," Both","three"," Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve" }; Parallelloopresult result=Parallel.ForEach<string> (data, S ={Console.WriteLine (s); }); Parallel.ForEach<string>(data, (s, pls, l)={Console.WriteLine ("{0} {1}", S, l); });
4. Calling multiple methods via the Parallel.Invoke () method
Static void Parallelinvoke () { Parallel.Invoke (Foo, Bar); } Static void Foo () { Console.WriteLine ("foo"); } Static void Bar () { Console.WriteLine ("bar"); }
Recommended reading: Recommendations for improving C # programs 10: Simplifying tasks with parallel
Parallel Class (simplified task operation)