This example tries to demonstrate the functionality of parallel processing in the most concise code, which uses single-threaded and multi-threaded operations 5 times in a 1-second time, respectively. Print out the execution process and time-consuming.
The following is the sample code, which requires more than 4.0. NET Framework.
usingSystem;usingSystem.Collections.Generic;usingSystem.Collections.Concurrent;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceparalleldemo{classProgram {Static voidMain (string[] args) { //First do the sequential version.Console.WriteLine ("executing sequential loop ..."); Stopwatch Stopwatch=NewStopwatch (); Stopwatch. Start ();
Single Thread Execution for(inti =0; I <5; i++) {TestMethod (); } stopwatch. Stop (); Console.WriteLine ("sequential loop time in milliseconds: {0}", stopwatch. Elapsedmilliseconds); //Reset Timer and results matrix.stopwatch. Reset (); Console.WriteLine ("executing parallel loop ..."); Stopwatch. Start ();
Multithreaded Execution Parallel.For (0,5, i =TestMethod ()); Stopwatch. Stop (); Console.WriteLine ("Parallel loop time in milliseconds: {0}", stopwatch. Elapsedmilliseconds); //Keep the console window open in debug mode.Console.WriteLine ("Press any key to exit."); Console.readkey (); } Static voidTestMethod () {varTid =Thread.CurrentThread.ManagedThreadId; Console.WriteLine ("Thread {0} start", Tid); Thread.Sleep ( +); Console.WriteLine ("Thread {0} end", Tid); } }}
Run results
Executing sequential loop ... Thread 9 Startthread 9 Endthread 9 Startthread 9 Endthread 9 Startthread 9 Endthread 9 Startthread 9 Endthread 9 StartThre Ad 9 Endsequential looptime in milliseconds:5004 executing parallel loop ... Thread 9 startthread startthread one startthread startthread startthread 9 endthread endthread one Endthread 12 Endthread EndParallel looptime in milliseconds:1024 Press any key to exit.
Attached: official example
A simple example to read. Net parallel programming