關於Thread ThreadPool Parallel 的一些小測試demo

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;

namespace TestProject
{
    class Program
    {
        //異步:不阻塞主線程的一種編程方法
        //多線程(new Thread): 多個線程去作一個事情 (注意共享變量的問題)(沒法監測是否完成)
        //線程池(new ThreadPool):省去線程重複建立回收的消耗。(沒法檢測執行任務是否完成)
        //Task: Task在線程池的基礎上進行了優化,而且能夠檢測到完成狀態。
        //Parallel:並行多個任務。(並且能監測完成狀態)
        //樂觀鎖悲觀鎖
        static void Main(string[] args)
        {
            //int a = 0;
            Stopwatch stopwatch = new Stopwatch();

            #region 單線程
            stopwatch.Start(); // 開始監視代碼運行時間
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("thread:{0}", Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(100);
            }
            // you code ....
            stopwatch.Stop(); // 中止監視
            ConsoleTime(stopwatch, "單線程");
            #endregion

            #region ThreadPool(沒辦法檢測是否完成哦!)這裏監測到的時間是建立線程池所須要的時間
            stopwatch.Start(); // 開始監視代碼運行時間

            ThreadPool.SetMaxThreads(5, 5);
            ThreadPool.SetMinThreads(1, 1);
            for (int i = 0; i < 10; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
                {
                    Console.WriteLine("線程池輸出: thread:{0}", Thread.CurrentThread.ManagedThreadId);
                    Thread.Sleep(100);
                }), i.ToString());
            }
            // you code ....
            stopwatch.Stop(); // 中止監視
            ConsoleTime(stopwatch, "ThreadPool");
            #endregion

            #region Thread(沒辦法檢測完成!沒有返回值沒有辦法檢測狀態。)這裏監測到的時間僅僅只是建立這些線程所須要的時間。
            stopwatch.Start(); // 開始監視代碼運行時間
            for (int i = 0; i < 10; i++)
            {
                Thread thread = new Thread(new ThreadStart(DoSomeThing));
                thread.Start();
                //Thread.Sleep(100);
            }
            // you code ....
            stopwatch.Stop(); // 中止監視
            ConsoleTime(stopwatch, "Thread");
            #endregion

            #region Parallel
            stopwatch.Start(); // 開始監視代碼運行時間
            var task = System.Threading.Tasks.Parallel.For(0, 10, new ParallelOptions() { MaxDegreeOfParallelism = 2 }, (i) =>
               {
                   Console.WriteLine("{0},task:{1},thread:{2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
                   Task.Delay(1000);
                   //提供的原子性操做,保證對a的值操做每一次都是原子性的
                   //System.Threading.Interlocked.Add(ref a, 1);
                   //a++;
               });
            stopwatch.Stop(); // 中止監視
            ConsoleTime(stopwatch, "Parallel");
            #endregion

            //Console.Write(a);
            Console.ReadKey();
        }
        /// <summary>
        /// 模擬作點什麼同時輸出當前線程id
        /// </summary>
        private static void DoSomeThing()
        {
            Console.WriteLine("DoSomeThing: thread:{0}", Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(100);
        }
        /// <summary>
        /// 模擬異步執行方法
        /// </summary>
        /// <returns></returns>
        private static async Task DoSomeThing2()
        {
            await Task.Run(() =>
            {
                Console.WriteLine("DoSomeThing2: task:{0},thread:{1}", Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(1000);
            }
            );
        }
        //輸出當前代碼段運行時間
        private static void ConsoleTime(Stopwatch stopwatch, string BlockName)
        {
            TimeSpan timespan = stopwatch.Elapsed;  //獲取當前實例測量得出的總時間
            Console.WriteLine("{0} ,代碼執行時間:{1}(毫秒)", BlockName, timespan.TotalMilliseconds);  //總毫秒數
            stopwatch.Reset();
        }


    }
}
相關文章
相關標籤/搜索