请教c#的threadPool是怎么用的
发布网友
发布时间:2022-04-29 00:24
我来回答
共2个回答
热心网友
时间:2022-06-26 09:06
可以讲ThreadPool理解成一个“专门执行后台线程的人”。用法挺简单的
using System;
using System.Threading;
public class Example
{
public static void Main()
{
// 由线程池启动一个后台线程
ThreadPool.QueueUserWorkItem(new WaitCallback(MyThreadProc));
//主线程休眠1秒,等待线程池执行MyThreadProc
Thread.Sleep(1000);
Console.WriteLine("程序结束!");
}
// 这个是由线程池执行的线程.
static void MyThreadProc(Object stateInfo)
{
Console.WriteLine("这是由线程池所执行线程打印的信息");
}
}
热心网友
时间:2022-06-26 09:07
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();
}
}
}