一、Parallel.Invoke执行多个方法
没有特定执行顺序,利用cpu多核并发执行
#region Parallel.Invoke Stopwatch watch = new Stopwatch(); watch.Start(); Parallel.Invoke(Pinvoke1, Pinvoke2); watch.Stop(); Console.WriteLine("Parallel run " + watch.ElapsedMilliseconds + " ms"); watch.Reset(); watch.Start(); Pinvoke1(); Pinvoke2(); watch.Stop(); Console.WriteLine("Normal run " + watch.ElapsedMilliseconds + " ms"); Console.ReadKey(); #endregion Parallel.Invoke
private static void Pinvoke1() { Thread.Sleep(3000); Console.WriteLine("Pinvoke1 ThreadId="+Thread.CurrentContext.ContextID); } private static void Pinvoke2() { Thread.Sleep(2000); Console.WriteLine("Pinvoke2 ThreadId=" + Thread.CurrentContext.ContextID); }
结果:
二、Parallel.For 有空再接着写