C# 应用 - 多线程 2) Thread 和 ThreadPool
IEnumerable<int> intList = Enumerable.Range(1, 15);
foreach (int i in intList)
{
ThreadPool.QueueUserWorkItem(w =>
{
Console.WriteLine("ThreadPool:" + Thread.CurrentThread.ManagedThreadId.ToString());
});
}
foreach ( int i in intList)
{
new Thread(new ThreadStart(() =>
{
Console.WriteLine("Thread:" + Thread.CurrentThread.ManagedThreadId.ToString());
})).Start();
}
结果:
Thread:16
Thread:10
ThreadPool:4
ThreadPool:9
ThreadPool:9
ThreadPool:9
ThreadPool:9
ThreadPool:9
ThreadPool:9
ThreadPool:9
ThreadPool:9
ThreadPool:9
Thread:17
Thread:18
Thread:19
Thread:20
Thread:21
Thread:22
Thread:23
Thread:24
ThreadPool:4
ThreadPool:6
ThreadPool:5
ThreadPool:7
ThreadPool:8
Thread:12
Thread:13
Thread:14
Thread:15
如果有大量的任务需要处理,例如处理 http 请求时如果对每个请求都创建一个后台线程,会占用大量的内存,而且频繁的创建也会影响速度。而线程池会把创建的线程存起来,形成一个线程池
因此:处理简单的耗时任务时,我们可以使用线程池技术来处理,而不是手动开辟线程来处理耗时任务.