如何讓代碼執行得更快,如何充分發揮多核CPU的性能,是程序員須要思考的問題. 本文經過簡單易懂的實例,讓你們快速瞭解C#多線程的基本方法.html
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace parallelInvoke { public class program { public static void Main(String[] args) { parallelInvokeMthod pi = new parallelInvokeMthod(); pi.Method1(); pi.Method2(); } } class parallelInvokeMthod { private Stopwatch stopWatch = new Stopwatch(); // Run1 taks 1s public void Run1() { Thread.Sleep(1000); Console.WriteLine("Run1 = 1s" ); } // Run2 taks 3s` public void Run2() { Thread.Sleep(3000); Console.WriteLine("Run2 = 3s"); } // Run1 and Run2 take 4s by using Parallel.Invoke() public void Method1() { stopWatch.Start(); Parallel.Invoke(Run1,Run2); stopWatch.Stop(); Console.WriteLine("Method1 total run time is " + stopWatch.ElapsedMilliseconds +" ms"); } //Run1 and Run2 take 6s by using normall method public void Method2() { stopWatch.Restart(); Run1(); Run2(); stopWatch.Stop(); Console.WriteLine("Method2 total run time is " + stopWatch.ElapsedMilliseconds+" ms"); } } }