• .NET多线程小记(4):线程池


    .NET线程池

    线程池中运行的线程都为后台线程,线程的IsBackground属性都会被设为true.所谓的后台线程是指这些线程的运行不会阻碍应用程序的结束。相反的,应用程序必须等待所有前台线程结束后才能退出。

    示例

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace MultiThreadTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                String taskObject = "Running 10 seconds";
    
                bool result = ThreadPool.QueueUserWorkItem(Task, taskObject);
                if (!result)
                    Console.WriteLine("Can't get thread");
                else
                    Console.WriteLine("Press Enter to exit");
                Console.Read();
            }
    
            static void Task(object state)
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine(state+" Thread Id is "+Thread.CurrentThread.ManagedThreadId.ToString());
                    Thread.Sleep(1000);
    
                }
            }
        }
    }

    如果用户在程序运行过程中按下任意键,程序会立刻中止。

    System.Threading.ThreadPool类型封装了线程池的操作,每个进程拥有一个线程池,.NET提供了线程池管理的机制,用户只需要把线程需求插入到线程池中,而不必再理会后续的工作。所有线程池中的线程都是后台线程,他们不会阻碍程序的退出。

  • 相关阅读:
    安装完MySQL数据库设置密码
    pom.xml
    性能测试更像一次科学实验
    gitlab git
    postman
    python3 session cookie
    自动化测试的概念及工具
    项目启动加载配置,以及IP黑名单,使用CommandLineRunner和ApplicationRunner来实现(一般用在网关进行拦截黑名单)
    使用JWT登录生成token
    国际化的实现i18n--错误码国际化以及在springboot项目中使用
  • 原文地址:https://www.cnblogs.com/cnblogsfans/p/1597444.html
Copyright © 2020-2023  润新知