关于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();
        }


    }
}
原文地址:https://www.cnblogs.com/chongyao/p/10702262.html