菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
176
0

线程池

原创
05/13 14:22
阅读数 45263

线程池与线程的不同

线程的创建是比较占用资源的一件事情,.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

发表评论

0/200
176 点赞
0 评论
收藏
为你推荐 换一批