using System;
using System.Threading;
public class ThreadPooling {
public static void WorkerProcess(object state) {
for (;;) { // infinite task
Thread.Sleep(2000);
Console.WriteLine("WorkerProcess: {0}", state);
}
}
public static void TinyWorkerProcess(object state) {
Thread.Sleep(5000); // short task
Console.WriteLine("TinyWorkerProcess: {0}", state);
}
public static void Main(string[] argv) {
int workers; // worker threads
int asyncIOs; // asynchronous I/O threads
// How many worker and async. I/O threads are at most available for the various tasks?
ThreadPool.GetMaxThreads(out workers,out asyncIOs);
Console.WriteLine("max. worker threads: {0}", workers);
Console.WriteLine("max. asynchronous I/O threads: {0}", asyncIOs);
// register three tasks that run forever
for(int i = 0; i < 3; i++)
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkerProcess), i);
// add three further tasks that take at most 5000 ms before they terminate
for(int i = 0; i < 3; i++)
ThreadPool.QueueUserWorkItem(new WaitCallback(TinyWorkerProcess), i);
// permanently monitor the number of available worker threads
for (;;) {
Thread.Sleep(5000);
ThreadPool.GetAvailableThreads(out workers, out asyncIOs);
Console.WriteLine("currently available worker threads: {0}", workers);
}
}
}
|