C#多线程实例之Parallel.Invoke()

简介

如何让代码执行得更快,如何充分发挥多核CPU的性能,是程序员须要思考的问题. 本文经过简单易懂的实例,让你们快速了解C#多线程的基本方法.html

参考文档: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");
    }

}
}

执行结果

相关文章
相关标签/搜索