zoukankan      html  css  js  c++  java
  • 线程池

    线程池与线程的不同

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

  • 相关阅读:
    Windows Phone 的控件倾斜效果
    在framework4.0 3.5中反序列化 解析JSON
    PhpStorm2.0、3.0,5.0注册码到2112年
    Windows Phone(wp7)系统长按的秘密
    配置ethereal编译环境
    复习C++:引用的一些用法
    转载
    Stay hungry,Stay foolish
    C++:继承的一点注意事项
    纯虚函数
  • 原文地址:https://www.cnblogs.com/mcgrady/p/5653018.html
Copyright © 2011-2022 走看看