using System;
using System.Threading;
namespace ThreadPoolTest
{
class MainApp
{
static void Main()
{
WaitCallback callBack;
callBack = new WaitCallback(PooledFunc);
ThreadPool.QueueUserWorkItem(callBack,
"Is there any screw left?");
ThreadPool.QueueUserWorkItem(callBack,
"How much is a 40W bulb?");
ThreadPool.QueueUserWorkItem(callBack,
"Decrease stock of monkey wrench");
Console.ReadLine();
}
static void PooledFunc(object state)
{
Console.WriteLine("Processing request '{0}'", (string)state);
// Simulation of processing time
Thread.Sleep(2000);
Console.WriteLine("Request processed");
}
}
}
我们可以通过在两个方法中加入如下的代码,以此看到更多的信息。
// Main method
Console.WriteLine("Main thread. Is pool thread: {0}, Hash: {1}",
Thread.CurrentThread.IsThreadPoolThread,
Thread.CurrentThread.GetHashCode());
// Pool method
Console.WriteLine("Processing request '{0}'." +
" Is pool thread: {1}, Hash: {2}",
(string)state, Thread.CurrentThread.IsThreadPoolThread,
Thread.CurrentThread.GetHashCode());
本文通过一个具体的C#线程池使用实例,展示了如何利用线程池来提高应用程序的效率。介绍了如何创建WaitCallback委托并将其排队到线程池进行处理。

4万+

被折叠的 条评论
为什么被折叠?



