using System;
using System.Threading;
public class SimplePool
{
public static int Main(string[] args)
{
//當前系統是否支援執行緒集區
bool flag = false;
//允許執行緒集區中運行最多10個執行緒
int MaxCount = 10;
//新建ManualResetEvent物件並且初始化為無信號狀態
ManualResetEvent mrevent = new ManualResetEvent(false);
Console.WriteLine("Queuing {0} items to Thread Pool", MaxCount);
OperThread operThread = new OperThread(MaxCount);
//建立工作項
//初始化operThread物件的mrevent 屬性
operThread.mrevent = mrevent;
Console.WriteLine("Queue to Thread Pool 0");
try
{
//將工作項裝入執行緒集區
//這裡要用Win200以上版本才有的API
//所以可能會出現NotSupportException例外
ThreadPool.QueueUserWorkItem(new WaitCallback(operThread.Beta), new StateInfo(0));
flag = true;
}
catch (NotSupportedException e)
{
Console.WriteLine(e.Message);
flag = false;
}
if (flag)
{
for (int iItem = 1; iItem < MaxCount; iItem++)
{
//插入序列元素
Console.WriteLine("Queue to Thread Pool {0}", iItem);
ThreadPool.QueueUserWorkItem(new WaitCallback(operThread.Beta), new StateInfo(iItem));
}
Console.WriteLine("Waiting for Thread Pool to drain");
//等待事件的完成,即執行緒叫用ManualResetEvent.Set方法
mrevent.WaitOne(Timeout.Infinite, true);
//WaitOne方法使叫用它的執行緒等待直到mrevent.Set方法被叫用
Console.WriteLine("Thread Pool has been drained (Event fired)");
Console.WriteLine();
Console.WriteLine("Load acrooss threads");
foreach (object o in operThread.HashCount.Keys)
Console.WriteLine("{0} {1}", o, operThread.HashCount[o]);
}
Console.ReadLine();
return 0;
}
}
沒有留言:
張貼留言