UseThreads为手工线程
UseThreadPool为线程池方式
static void Main(string[] args)
{
const int numberOfOperations = 500;
var sw = new Stopwatch();
sw.Start();
UseThreads(numberOfOperations);
sw.Stop();
Console.WriteLine("execute time using threads: {0}", sw.ElapsedMilliseconds);
//相对于上一种方式,可节约运行空间,但需支付更多的运行时间
sw.Reset();
sw.Start();
UseThreadPool(numberOfOperations);
sw.Stop();
Console.WriteLine("execution time using threads: {0}", sw.ElapsedMilliseconds);
Console.ReadKey();
}
static void UseThreads(int numberOfOperations)
{
using (var countdown = new CountdownEvent(numberOfOperations))
{
Console.WriteLine("scheduling work by creating threads");
for(int i = 0; i < numberOfOperations; i++)
{
var thread = new Thread(() =>
{
//Console.Write("{0},", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(0.1));
countdown.Signal();
});
thread.Start();
}
countdown.Wait();
Console.WriteLine();
}
}
static void UseThreadPool(int numberOfOperations)
{
using (var countdown = new CountdownEvent(numberOfOperations))
{
Console.WriteLine("startingt work on a threadpool");
for(int i = 0; i < numberOfOperations; i ++)
{
ThreadPool.QueueUserWorkItem(_ =>
{
//Console.WriteLine("{0},", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(0.1));
countdown.Signal();
});
}
countdown.Wait();
Console.WriteLine();
}
}