using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics ;
using static System.Console;
using System.Threading;
using static System.Threading.Thread;
namespace BookSample
{
class Program
{
static void UseThreads(int numberOfOperations)
{
//用到了using statement,CountdownEvent实现了IDisposible接口,最后要显示调用dipose(),但用这
//样的using语句,在using语句中实例化,在花括号的using块中写上原本try中的内容,结束后会自动调用
//Dispose()释放非托管资源。
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.WriteLine($"{CurrentThread.ManagedThreadId},");
Sleep(TimeSpan.FromSeconds(0.1));
//Signal是让CountdownEvent中的计数减一。
countdown.Signal();
});
thread.Start();
}
//Wait阻塞当前线程,直到CountdownEvent中计数减到零。
countdown.Wait();
WriteLine();
}
}
static void UseThreadPool(int numberOfOperations)
{
using (var countdown = new CountdownEvent(numberOfOperations))
{
Console.WriteLine("Starting work on a threadpool");
for (int i = 0; i < numberOfOperations; i++)
{
//将线程放入线程池不能也不用手动开始。
ThreadPool.QueueUserWorkItem(_=>
{
Write($"{CurrentThread.ManagedThreadId},");
Sleep(TimeSpan.FromSeconds(0.1));
countdown.Signal();
}
);
}
countdown.Wait();
WriteLine();
}
}
static void Main(string[] args)
{
const int numberOfOperations = 500;
var sw = new Stopwatch();
sw.Start();
UseThreads(numberOfOperations);
sw.Stop();
WriteLine($"Execution time using threads:{sw.ElapsedMilliseconds}");
sw.Reset();
sw.Start();
UseThreadPool(numberOfOperations);
sw.Stop();
WriteLine($"Excution time using the thread pool:{sw.ElapsedMilliseconds}");
Console.Read();
}
}
}
程序来自 C# 多线程编程时间(原书第二版)