也许你曾经遇到过:一个线程做事情,其他线程等待,那么有可能因为不做事情的线程在等待,而浪费掉时间。
我们可以通过线程池ThreadPool来解决,使用ThreadPool.QueueUserWorkItem(回调函数,object),将参数封装在一个类的对象中,传给回调函数去执行。
TheadPool的用法:
1、创建一个ManualResetEvent的对象,就像一个信号灯,指示线程的挂起和执行;
2、ManualResetEvent对象创建时,可以指定默认状态:true为有信号,false为无信号;
3、调用Reset()方法重置状态;
4、调用WaitOne()方法,使线程处于等待状态;
5、调用Set()方法设置状态。
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading;
- using System.Collections;
- namespace Demo
- {
- public class ParamObject
- {
- public int number;
- public ParamObject (int number)
- {
- this.number = number;
- }
- }
- public class ThreadClass
- {
- public Hashtable aHashTable;
- public ManualResetEvent aManualResetEvent;
- public static int iCount = 0;
- public static int iMaxCount = 0;
- public ThreadClass(int maxCount)
- {
- aHashTable = new Hashtable(maxCount);
- iMaxCount = maxCount;
- }
- public void ThreadRun(object aParamObject)
- {
- Console.WriteLine("HashCode: {0}, Number in Object: {1}", Thread.CurrentThread.GetHashCode(), ((ParamObject)aParamObject).number);
- lock (aHashTable)
- {
- if (!aHashTable.ContainsKey(Thread.CurrentThread.GetHashCode()))
- {
- aHashTable.Add(Thread.CurrentThread.GetHashCode(), 0);
- }
- aHashTable[Thread.CurrentThread.GetHashCode()] = (int)aHashTable[Thread.CurrentThread.GetHashCode()] + 1;
- }
- Thread.Sleep(3000);
- Interlocked.Increment(ref iCount);
- if (iCount == iMaxCount)
- {
- Console.WriteLine("Setting aManualResetEvent...");
- aManualResetEvent.Set();
- }
- }
- }
- class Program
- {
- public static void Main(string[] args)
- {
- bool enableThreadPool = false;
- int iMaxCount = 20;
- ManualResetEvent aManualResetEvent = new ManualResetEvent(false);
- Console.WriteLine("Insert {0} items to Thread Pool.", iMaxCount);
- ThreadClass aThreadClass = new ThreadClass(iMaxCount);
- aThreadClass.aManualResetEvent = aManualResetEvent;
- // First, add an item to check if your system supports ThreadPool API function or not.
- try
- {
- ThreadPool.QueueUserWorkItem(new WaitCallback(aThreadClass.ThreadRun), new ParamObject(0));
- enableThreadPool = true;
- }
- catch (NotSupportedException ex)
- {
- Console.WriteLine("Thread Pool API is not supported in this system.");
- enableThreadPool = false;
- }
- if (enableThreadPool)
- {
- for (int i = 1; i < iMaxCount; i++)
- {
- ThreadPool.QueueUserWorkItem(new WaitCallback(aThreadClass.ThreadRun), new ParamObject(i));
- }
- Console.WriteLine("Waiting for thread pool to drain");
- aManualResetEvent.WaitOne(Timeout.Infinite, true);
- Console.WriteLine("Thread Pool has been drained.");
- Console.WriteLine("Load threads info:");
- foreach (object key in aThreadClass.aHashTable.Keys)
- {
- Console.WriteLine("Key: {0}, Value: {1}", key, aThreadClass.aHashTable[key]);
- }
- }
- Console.ReadLine();
- }
- }
- }
本文介绍如何利用线程池技术解决线程等待导致的时间浪费问题,并通过示例展示手动重置事件信号灯的用法,实现高效并发任务执行。
1524

被折叠的 条评论
为什么被折叠?



