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.
上一篇:取之开源,用之开源——深度剖析阿里巴巴对Apache Flink的优化与改进


下一篇:从奔腾I的VCD播放到AI区块链播放器——程序优化的魔法