C#多线程——线程池和回调函数

本文介绍如何利用线程池技术解决线程等待导致的时间浪费问题,并通过示例展示手动重置事件信号灯的用法,实现高效并发任务执行。
部署运行你感兴趣的模型镜像

也许你曾经遇到过:一个线程做事情,其他线程等待,那么有可能因为不做事情的线程在等待,而浪费掉时间。

我们可以通过线程池ThreadPool来解决,使用ThreadPool.QueueUserWorkItem(回调函数,object),将参数封装在一个类的对象中,传给回调函数去执行。

TheadPool的用法:

1、创建一个ManualResetEvent的对象,就像一个信号灯,指示线程的挂起和执行;

2、ManualResetEvent对象创建时,可以指定默认状态:true为有信号,false为无信号;

3、调用Reset()方法重置状态;

4、调用WaitOne()方法,使线程处于等待状态;

5、调用Set()方法设置状态。

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Threading;  
  5. using System.Collections;  
  6.   
  7. namespace Demo  
  8. {  
  9.     public class ParamObject  
  10.     {  
  11.         public int number;  
  12.         public ParamObject (int number)  
  13.         {  
  14.             this.number = number;  
  15.         }  
  16.     }  
  17.   
  18.     public class ThreadClass  
  19.     {  
  20.         public Hashtable aHashTable;  
  21.         public ManualResetEvent aManualResetEvent;  
  22.         public static int iCount = 0;  
  23.         public static int iMaxCount = 0;  
  24.   
  25.         public ThreadClass(int maxCount)  
  26.         {  
  27.             aHashTable = new Hashtable(maxCount);  
  28.             iMaxCount = maxCount;  
  29.         }  
  30.   
  31.         public void ThreadRun(object aParamObject)  
  32.         {  
  33.             Console.WriteLine("HashCode: {0}, Number in Object: {1}", Thread.CurrentThread.GetHashCode(), ((ParamObject)aParamObject).number);  
  34.             lock (aHashTable)  
  35.             {  
  36.                 if (!aHashTable.ContainsKey(Thread.CurrentThread.GetHashCode()))  
  37.                 {  
  38.                     aHashTable.Add(Thread.CurrentThread.GetHashCode(), 0);  
  39.                 }  
  40.                 aHashTable[Thread.CurrentThread.GetHashCode()] = (int)aHashTable[Thread.CurrentThread.GetHashCode()] + 1;  
  41.             }  
  42.             Thread.Sleep(3000);  
  43.               
  44.             Interlocked.Increment(ref iCount);  
  45.             if (iCount == iMaxCount)  
  46.             {  
  47.                 Console.WriteLine("Setting aManualResetEvent...");  
  48.                 aManualResetEvent.Set();  
  49.             }  
  50.         }  
  51.     }  
  52.   
  53.     class Program  
  54.     {  
  55.        public static void Main(string[] args)  
  56.        {  
  57.            bool enableThreadPool = false;  
  58.            int iMaxCount = 20;  
  59.            ManualResetEvent aManualResetEvent = new ManualResetEvent(false);  
  60.   
  61.            Console.WriteLine("Insert {0} items to Thread Pool.", iMaxCount);  
  62.            ThreadClass aThreadClass = new ThreadClass(iMaxCount);  
  63.            aThreadClass.aManualResetEvent = aManualResetEvent;  
  64.   
  65.            // First, add an item to check if your system supports ThreadPool API function or not.  
  66.            try  
  67.            {  
  68.                ThreadPool.QueueUserWorkItem(new WaitCallback(aThreadClass.ThreadRun), new ParamObject(0));  
  69.                enableThreadPool = true;  
  70.            }  
  71.            catch (NotSupportedException ex)  
  72.            {  
  73.                Console.WriteLine("Thread Pool API is not supported in this system.");  
  74.                enableThreadPool = false;  
  75.            }  
  76.   
  77.            if (enableThreadPool)  
  78.            {  
  79.                for (int i = 1; i < iMaxCount; i++)  
  80.                {  
  81.                    ThreadPool.QueueUserWorkItem(new WaitCallback(aThreadClass.ThreadRun), new ParamObject(i));  
  82.                }  
  83.                Console.WriteLine("Waiting for thread pool to drain");  
  84.                aManualResetEvent.WaitOne(Timeout.Infinite, true);  
  85.   
  86.                Console.WriteLine("Thread Pool has been drained.");  
  87.                Console.WriteLine("Load threads info:");  
  88.                foreach (object key in aThreadClass.aHashTable.Keys)  
  89.                {  
  90.                    Console.WriteLine("Key: {0}, Value: {1}", key, aThreadClass.aHashTable[key]);  
  91.                }  
  92.            }  
  93.            Console.ReadLine();  
  94.        }  
  95.     }  
  96. }  

您可能感兴趣的与本文相关的镜像

Qwen3-8B

Qwen3-8B

文本生成
Qwen3

Qwen3 是 Qwen 系列中的最新一代大型语言模型,提供了一整套密集型和专家混合(MoE)模型。基于广泛的训练,Qwen3 在推理、指令执行、代理能力和多语言支持方面取得了突破性进展

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值