How to use QueueUserWorkItem in C# ThreadPool?
The ThreadPool.QueueUserWorkItem method allows you to add work items to the thread pool queue for execution on an available thread in the thread pool. Here is a basic example of using ThreadPool.QueueUserWorkItem:
using System;
using System.Threading;
class Program
{
static void Main()
{
for (int i = 0; i < 10; i++)
{
ThreadPool.QueueUserWorkItem(DoWork, i);
}
Console.WriteLine("All work items queued.");
Console.ReadLine();
}
static void DoWork(object state)
{
int workItemNum = (int)state;
Console.WriteLine("Work item {0} starting.", workItemNum);
Thread.Sleep(1000); // 模拟工作
Console.WriteLine("Work item {0} completed.", workItemNum);
}
}
In the example above, we use the ThreadPool.QueueUserWorkItem method to add 10 work items to the thread pool queue. Each work item is an integer representing the work number. In the DoWork method, we simulate a long-running task and print a message when the work is completed.
Please note that the ThreadPool.QueueUserWorkItem method adds work items to the thread pool, where available threads are automatically assigned to execute them. Once the work item is completed, the thread will return to the thread pool for reuse.