你的位置:首页 > 软件开发 > ASP.net > C#多线程之线程池篇2

C#多线程之线程池篇2

发布时间:2016-12-28 10:00:34
在上一篇C#多线程之线程池篇1中,我们主要学习了如何在线程池中调用委托以及如何在线程池中执行异步操作,在这篇中,我们将学习线程池和并行度、实现取消选项的相关知识。三、线程池和并行度  在这一小节中,我们将学习对于大量的异步操作,使用线程池和分别使用单独的线程在性能上有什么差异性。 ...

C#多线程之线程池篇2

  在上一篇C#多get='_blank'>线程之线程池篇1中,我们主要学习了如何在线程池中调用委托以及如何在线程池中执行异步操作,在这篇中,我们将学习线程池和并行度、实现取消选项的相关知识。

三、线程池和并行度

  在这一小节中,我们将学习对于大量的异步操作,使用线程池和分别使用单独的线程在性能上有什么差异性。具体操作步骤如下:

1、使用Visual Studio 2015创建一个新的控制台应用程序。

2、双击打开“Program.cs”文件,编写代码如下所示:

 1 using System; 2 using System.Diagnostics; 3 using System.Threading; 4 using static System.Console; 5 using static System.Threading.Thread; 6  7 namespace Recipe03 8 { 9   class Program10   {11     static void UseThreads(int numberOfOperations)12     {13       using(var countdown=new CountdownEvent(numberOfOperations))14       {15         WriteLine("Scheduling work by creating threads");16         for(int i = 0; i < numberOfOperations; i++)17         {18           var thread = new Thread(() =>19            {20              Write($"{CurrentThread.ManagedThreadId},");21              Sleep(100);22              countdown.Signal();23            });24           thread.Start();25         }26         countdown.Wait();27         WriteLine();28       }29     }30 31     static void UseThreadPool(int numberOfOperations)32     {33       using(var countdown=new CountdownEvent(numberOfOperations))34       {35         WriteLine("Starting work on a threadpool");36         for(int i = 0; i < numberOfOperations; i++)37         {38           ThreadPool.QueueUserWorkItem(_ =>39           {40             Write($"{CurrentThread.ManagedThreadId},");41             Sleep(100);42             countdown.Signal();43           });44         }45         countdown.Wait();46         WriteLine();47       }48     }49 50     static void Main(string[] args)51     {52       const int numberOfOperations = 500;53       var sw = new Stopwatch();54       sw.Start();55       UseThreads(numberOfOperations);56       sw.Stop();57       WriteLine($"Execution time using threads: {sw.ElapsedMilliseconds}");58 59       sw.Reset();60       sw.Start();61       UseThreadPool(numberOfOperations);62       sw.Stop();63       WriteLine($"Execution time using the thread pool: {sw.ElapsedMilliseconds}");64     }65   }66 }

原标题:C#多线程之线程池篇2

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录