Parallel


Parallel參考網站1 Parallel參考網站2

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ParallelDemo
{

    class Program
    {
        static int count1 = 0;
        static int count2 = 0;

        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Reset();
            sw.Start();

            var syncObject = new object();
            int t1, t2, t3;

            #region Parallel For
            //Parallel.For(0, 10, (i, loopState) =>
            //{
            //    if (i > 5)
            //    {
            //        //loopState.Stop(); 表示永久跳出這個迴圈,不論後面的Index是否滿足 i > 5 這個條件。
            //        loopState.Stop();
            //        //loopState.Break(); 表示若當前Index的資料滿足 i > 5 的迴圈則Continue跳下一筆Index。
            //        //loopState.Break();
            //        return;
            //    }

            //    Console.WriteLine(i);
            //});
            #endregion

            //有時候用Parrel的效能並不會比for好
            Program objA = new Program();
            //objA.ParallelFor();
            //objA.For();

            #region Parallel Invoke
            //Parallel.Invoke(
            //    () => t1 = Task1(),
            //    () => t2 = Task2(),
            //    () => t3 = Task3());
            #endregion


            sw.Stop();
            Console.WriteLine("共耗時:" + sw.ElapsedMilliseconds);
            Console.ReadLine();
        }

        public void ParallelFor()
        {
            Parallel.For(0, 10, (i, loopState) =>
            {
                lock (this)
                {
                    //在這邊lock起來,使共享的變數不會互相干擾
                    count1 += Task1();
                    count1 += Task2();
                }
            });

            Console.WriteLine(count1);
        }

        public void For()
        {
            for (int j = 0; j < 10; j++)
            {
                count2 += Task1();
                count2 += Task2();
            }

            Console.WriteLine(count2);
        }

        public static int Task1()
        {
            Task.Delay(200).Wait();
            return 1;
        }
        public static int Task2()
        {
            Task.Delay(300).Wait();
            return 1;
        }
        public static int Task3()
        {
            Task.Delay(500).Wait();
            return 3;
        }
    }
}

results matching ""

    No results matching ""