C#多線程實例之Parallel.Invoke()

簡介

如何讓代碼執行得更快,如何充分發揮多核CPU的性能,是程序員需要思考的問題. 本文通過簡單易懂的實例,讓大家快速瞭解C#多線程的基本方法.

參考文檔:http://www.cnblogs.com/yunfeifei/p/3993401.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");
    }

}
}

執行結果

Run1 = 1s
Run2 = 3s
Method1 total run time is 3000 ms
Run1 = 1s
Run2 = 3s
Method2 total run time is 3999 ms

說明

  • 本例中, Run1執行1s, Run2執行3s, 採用Parallel.Invoke()方法,使之並行執行, 總共耗時3s.
  • 如果按照Method2()方法,順序執行Run1和Run2,則總共需要4s.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章