线程池

线程池与线程的不同

线程的创建是比较占用资源的一件事情,.NET 为我们提供了线程池来帮助我们创建和管理线程。Task是默认会直接使用线程池,但是Thread不会。如果我们不使用Task,又想用线程池的话,可以使用ThreadPool类。

Demo

上代码。

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading;
  6 using System.Threading.Tasks;
  7 
  8 namespace AsyncCoding
  9 {
 10     class Program
 11     {
 12         static void Main(string[] args)
 13         {
 14             ThreadPool.QueueUserWorkItem(Go1);//使用线程池,默认创建的是后台线程
 15 
 16             Console.WriteLine("我是主线程,Thread Id:{0}", Thread.CurrentThread.ManagedThreadId);
 17             Console.ReadKey();
 18         }
 19 
 20         public static void Go1(object state)
 21         {
 22             Console.WriteLine("我是异步线程,Thread Id:{0},是否为后台线程:{1}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsBackground);
 23             for (int i = 0; i < 10; i++)
 24             {
 25                 Thread.Sleep(100);//模拟每次执行需要100ms
 26                 Console.WriteLine("异步线程,Thread Id:{0},运行:{1}", Thread.CurrentThread.ManagedThreadId, i);
 27             }
 28         }
 29     }
 30 }
 31 
View Code

图解执行顺序。

2016-07-08_122124

运行结果。

image

原文地址:https://www.cnblogs.com/mcgrady/p/5653018.html