代码改变世界

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

2009-11-06 15:01  敏捷的水  阅读(570)  评论(0编辑  收藏  举报

.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提供了线程池管理的机制,用户只需要把线程需求插入到线程池中,而不必再理会后续的工作。所有线程池中的线程都是后台线程,他们不会阻碍程序的退出。