C# 线程池的使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadPoolExam
{
class Program
{
static void Main(string[] args)
{
int nWorkerThread;
int nCompletionPortThread;
ThreadPool.GetMaxThreads(out nWorkerThread, out nCompletionPortThread);//获取最大的工作线程和IO线程
Console.WriteLine("Max worker thread:{0},Max IO thread:{1}", nWorkerThread, nCompletionPortThread);
for (int i = 0; i < 5; i++)
{
ThreadPool.QueueUserWorkItem(JobForThread);//分配给线程池里的空闲线程执行
}
Thread.Sleep(3000);
Console.Read();
}
static void JobForThread(object state)
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Loop {0},running inside pooled thread {1}", i, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(50);
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadPoolExam
{
class Program
{
static void Main(string[] args)
{
int nWorkerThread;
int nCompletionPortThread;
ThreadPool.GetMaxThreads(out nWorkerThread, out nCompletionPortThread);//获取最大的工作线程和IO线程
Console.WriteLine("Max worker thread:{0},Max IO thread:{1}", nWorkerThread, nCompletionPortThread);
for (int i = 0; i < 5; i++)
{
ThreadPool.QueueUserWorkItem(JobForThread);//分配给线程池里的空闲线程执行
}
Thread.Sleep(3000);
Console.Read();
}
static void JobForThread(object state)
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Loop {0},running inside pooled thread {1}", i, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(50);
}
}
}
}