如何使用ThreadPool

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用ThreadPool相关的知识,希望对你有一定的参考价值。

参考技术A 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();


以上是关于如何使用ThreadPool的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot Async 方法如何使用 ThreadPool 处理请求

如何在 ThreadPool 中延迟执行?

[C#]如何使用ThreadPool

如何完成 ThreadPool.Join?

如何将信息从 ThreadPool.QueueUserWorkItem 传递回 UI 线程?

覆盖 Spring webflux 项目的默认 Threadpool 执行器的效果如何?