home *** CD-ROM | disk | FTP | other *** search
- /*============================================================
- **
- ** Class: SimplePool
- **
- ** Purpose: Simple Thread Pool Sample
- **
- ** Copyright (c) Microsoft, 1999-2000
- **
- ===========================================================*/
-
- using System;
- using System.Threading;
-
- public class SomeState
- {
- public int Cookie;
- public SomeState(int iCookie)
- {
- Cookie = iCookie;
- }
- };
-
- public class Alpha
- {
- public int [] HashCount;
- public ManualResetEvent eventX;
- public static int iCount = 0;
- public static int iMaxCount = 0;
- public Alpha(int MaxCount)
- {
- HashCount = new int[30];
- iMaxCount = MaxCount;
- }
-
- // The method that will be called when the Work Item is serviced
- // on the Thread Pool
- public void Beta(Object state)
- {
- Console.WriteLine(" {0} {1} :", Thread.CurrentThread.GetHashCode(), ((SomeState)state).Cookie);
- Interlocked.Increment(ref HashCount[Thread.CurrentThread.GetHashCode()]);
-
- // Do some busy work
- int iX = 10000;
- while (iX > 0)
- {
- iX--;
- }
- Interlocked.Increment(ref iCount);
- if (iCount == iMaxCount)
- {
- Console.WriteLine("");
- Console.WriteLine("Setting EventX ");
- eventX.Set();
- }
- }
- };
-
- public class SimplePool
- {
- public static int Main(String[] args)
- {
- Console.WriteLine("Thread Simple Thread Pool Sample");
- bool W2K = false;
- int MaxCount = 1000;
- ManualResetEvent eventX = new ManualResetEvent(false);
- Console.WriteLine("Queuing {0} items to Thread Pool", MaxCount);
- Alpha oAlpha = new Alpha(MaxCount);
- oAlpha.eventX = eventX;
- Console.WriteLine("Queue to Thread Pool 0");
- try
- {
- ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),new SomeState(0));
- W2K = true;
- }
- catch (NotSupportedException)
- {
- Console.WriteLine("These API's may fail when called on a non-Windows 2000 system.");
- }
- if (W2K)
- {
- for (int iItem=1;iItem < MaxCount;iItem++)
- {
- Console.WriteLine("Queue to Thread Pool {0}", iItem);
- ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),new SomeState(iItem));
- }
- Console.WriteLine("Waiting for Thread Pool to drain");
- eventX.WaitOne(Timeout.Infinite,true);
- Console.WriteLine("Thread Pool has been drained (Event fired)");
- Console.WriteLine("");
- Console.WriteLine("Load across threads");
- for(int iIndex=0;iIndex<oAlpha.HashCount.Length;iIndex++)
- Console.WriteLine("{0} {1}", iIndex, oAlpha.HashCount[iIndex]);
- }
- return 0;
- }
- }
-
-