Thread pool
Usage and Benefits
Example of Using Thread Pool in C#
using System;
using System.Threading;
public class Program
{
public static void Main()
{
// Queue some work to the thread pool
ThreadPool.QueueUserWorkItem(ProcessTask, 1);
ThreadPool.QueueUserWorkItem(ProcessTask, 2);
ThreadPool.QueueUserWorkItem(ProcessTask, 3);
// Wait for all tasks to complete (this is just for demonstration purposes)
Console.WriteLine("Tasks queued to thread pool.");
Console.ReadLine(); // Wait for user input to see the output
}
private static void ProcessTask(object state)
{
int taskId = (int)state;
Console.WriteLine($"Task {taskId} is processing on thread {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(1000); // Simulate some work
Console.WriteLine($"Task {taskId} has completed.");
}
}Conclusion
Last updated