Delegate、Thread、Task、ThreadPool几种方式创建异步任务性能对比
开始预测的结果是 Task>Delegate>ThreadPool>>Thread。
(一)测试代码
static async Task<int> AsyncTask(int i) { return i; } static void TestAsycnTask(int count) { for (int i = 0; i < count; i++) { AsyncTask(i); } } static void TestThread(int count) { for (int i = 0; i < count; i++) { new Thread(a =>{}).Start(); } } private delegate int _delegate(int i); static void TestDelegate(int count) { for (int i = 0; i < count; i++) { var d = new _delegate(Delegte); var r = d.BeginInvoke(i, null, null); } } static int Delegte(int i) { return i; } static void TestThreadPools(int count) { for(int i = 0; i < count; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback((object obj) => {})); } }
Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); TestDelegate(100); stopWatch.Stop(); Debug.WriteLine("TestDelegate:{0}", stopWatch.Elapsed); stopWatch.Restart(); TestAsycnTask(100); stopWatch.Stop(); Debug.WriteLine("TestAsycnTask:{0}", stopWatch.Elapsed); stopWatch.Restart(); TestThreadPools(100); stopWatch.Stop(); Debug.WriteLine("TestThreadPools:{0}", stopWatch.Elapsed); stopWatch.Restart(); TestThread(100); stopWatch.Stop(); Debug.WriteLine("TestThread:{0}", stopWatch.Elapsed);
(二)测试结果
(三)测试结论
1、线程方式效率是真的低。
2、线程池效率居然比Task还快,不知道为什么,也许测试方式有误。