Skip to content
标签
欢迎扫码关注公众号

使用 ThreadPool 代替 Thread

由于线程的创建和销毁代价比较高,使用到多线程时应首先考虑使用线程池。

避免线程过多中的例子修改为使用线程池。

示例代码

cs
using System;
using System.Threading;

namespace TooMuchThreadUseThreadPool
{
    class Program
    {
        static void Main(string args)
        {
            Console.WriteLine(DateTime.Now.ToString());
            for (int i = 0; i < 200; i++)
            {
                ThreadPool.QueueUserWorkItem((objState) =>
                {
                    int j = 1;
                    while (true)
                    {
                        j++;
                    }
                }, null);
            }
            Thread.Sleep(5000);
            ThreadPool.QueueUserWorkItem((objState) => {
                while (true)
                {
                    Console.WriteLine("{0}:T201 正在执行", DateTime.Now.ToString());
                }
            }, null);
            Console.WriteLine(DateTime.Now.ToString());
            Console.ReadKey();
        }
    }
}

虽然执行了一会还是没有 t201 线程的消息打出来到控制台,但是不阻塞主线程,两个时间都输出到控制台了。

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.