线程池与并行度 程序学习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics ;
using static System.Console;
using System.Threading;
using static System.Threading.Thread;


namespace BookSample
{
    
    

    class Program
    {
        static void UseThreads(int numberOfOperations)
        {
//用到了using statement,CountdownEvent实现了IDisposible接口,最后要显示调用dipose(),但用这
//样的using语句,在using语句中实例化,在花括号的using块中写上原本try中的内容,结束后会自动调用
//Dispose()释放非托管资源。
            using (var countdown = new CountdownEvent(numberOfOperations))
            {
                Console.WriteLine("scheduling work by creating threads");
                for (int i = 0; i < numberOfOperations; i++)
                {
                    var thread = new Thread
                        (()=>
                    {
                        Console.WriteLine($"{CurrentThread.ManagedThreadId},");
                        Sleep(TimeSpan.FromSeconds(0.1));
//Signal是让CountdownEvent中的计数减一。
                        countdown.Signal();
                    });
                    thread.Start();

                }
//Wait阻塞当前线程,直到CountdownEvent中计数减到零。
                countdown.Wait();

                WriteLine();

            }

        }

        static void UseThreadPool(int numberOfOperations)
        {
            using (var countdown = new CountdownEvent(numberOfOperations))
            {
                Console.WriteLine("Starting work on a threadpool");
                for (int i = 0; i < numberOfOperations; i++)
                {
//将线程放入线程池不能也不用手动开始。
                    ThreadPool.QueueUserWorkItem(_=>
                        {
                            Write($"{CurrentThread.ManagedThreadId},");
                            Sleep(TimeSpan.FromSeconds(0.1));
                            countdown.Signal();
                    }
                        );
                }
                countdown.Wait();
                WriteLine();
            }
        }








        static void Main(string[] args)
        {

            const int numberOfOperations = 500;
            var sw = new Stopwatch();
            sw.Start();
            UseThreads(numberOfOperations);
            sw.Stop();
            WriteLine($"Execution time using threads:{sw.ElapsedMilliseconds}");

            sw.Reset();
            sw.Start();
            UseThreadPool(numberOfOperations);
            sw.Stop();
            WriteLine($"Excution time using the thread pool:{sw.ElapsedMilliseconds}");


            Console.Read();





            
             
        }
    

    }

        
}

程序来自 C# 多线程编程时间(原书第二版)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值