[C#]『Parallel.Invoke』任务并行库使用小计

借助 Invoke(),您只需表述出希望要哪些操作同时运行,运行时将处理所有线程调度详情,包括依据主计算机上的内核数自动缩放。——MSDN

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                NormalInvoke();
                ParallelInvoke();
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Exception Message:{0}", ex.Message.Trim()));
            }
            finally
            {
                Console.ReadLine();
            }
        }
        static void NormalInvoke()
        {
            Stopwatch _wactch = new Stopwatch();
            _wactch.Start();
            doSomeWork();
            doOtherWork();
            _wactch.Stop();
            Console.WriteLine(string.Format("NormalInvoke cost time:{0}", _wactch.ElapsedMilliseconds));
        }
        static void ParallelInvoke()
        {
            Stopwatch _wactch = new Stopwatch();
            _wactch.Start();
            Parallel.Invoke(doSomeWork, doOtherWork);
            _wactch.Stop();
            Console.WriteLine(string.Format("ParallelInvoke cost time:{0}", _wactch.ElapsedMilliseconds));
        }
        static void doSomeWork()
        {
            Console.WriteLine("doSomeWork....");
            Thread.Sleep(3000);
        }
        static void doOtherWork()
        {
            Console.WriteLine("doOtherWork....");
            Thread.Sleep(5000);
        }
    }
}
 

代码效果

image

你可能感兴趣的:(C#)