1. 如何查看线程池的最大线程数和最小线程数
static void Main(string[] args)
{
Console.WriteLine("----------线程池开始,线程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId); int workthread;
int iothread; ThreadPool.GetMaxThreads(out workthread, out iothread);
Console.WriteLine("Max Work Thread:{0} Max I/O Thread:{1}",workthread,iothread); ThreadPool.GetMinThreads(out workthread, out iothread);
Console.WriteLine("Mix Work Thread:{0} Mix I/O Thread:{1}", workthread, iothread); Console.WriteLine("----------线程池结束,线程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId); Console.Read();
}
2. 如何设置线程池的最大线程数和最小线程数
static void Main(string[] args)
{
Console.WriteLine("----------线程池开始,线程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId); int workthread = 8;
int iothread = 8; ThreadPool.SetMaxThreads(workthread, iothread);
Console.WriteLine("Max Work Thread:{0} Max I/O Thread:{1}",workthread,iothread); ThreadPool.SetMinThreads(workthread, iothread);
Console.WriteLine("Mix Work Thread:{0} Mix I/O Thread:{1}", workthread, iothread); Console.WriteLine("----------线程池结束,线程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId); Console.Read();
}
3. ThreadPool线程启动
static void Main(string[] args)
{
Console.WriteLine("----------线程池开始,线程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId); for (int i = 0; i < 5; i++)
{
string name = string.Format("ThreadPool_{0}", i);
WaitCallback method = (t) => Program.TestThread(t.ToString());
ThreadPool.QueueUserWorkItem(method,name);
} Console.WriteLine("----------线程池结束,线程ID是{0}-----------------", Thread.CurrentThread.ManagedThreadId); Console.Read();
} static void TestThread(string name)
{
Console.WriteLine("TestThread Start name:{0} 当前线程id:{1} 当前时间:{2}", name, Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yy-MM-dd hh:mm:ss.fff")); long sum = 0; for (int i = 0; i < 10000000; i++)
{
sum += i;
} Console.WriteLine("TestThread End name:{0} 当前线程id:{1} 当前时间:{2}", name, Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yy-MM-dd hh:mm:ss.fff"));
}
4. ThreadPool线程回收
ThreadPool线程池会自动回收。
5. ThreadPool线程池等待
可以通过ManualResetEvent信号量来实现,代码如下:
6. ThreadPool返回值
没有提供方法,可以自己定义,代码如下:
7. ThreadPool回调方法
没有提供方法,可以自己定义,代码如下: