Delegate、Thread、Task、ThreadPool几种方式创建异步任务性能对比

时间:2021-04-15 02:03:06

开始预测的结果是 Task>Delegate>ThreadPool>>Thread。

(一)测试代码

 static async Task<int> AsyncTask(int i)
{
return i;
}
static void TestAsycnTask(int count)
{
for (int i = ; i < count; i++)
{
AsyncTask(i);
}
} static void TestThread(int count)
{
for (int i = ; i < count; i++)
{
new Thread(a =>{}).Start();
}
} private delegate int _delegate(int i);
static void TestDelegate(int count)
{
for (int i = ; 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 = ; i < count; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback((object obj) => {}));
}
}
       Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
TestDelegate();
stopWatch.Stop();
Debug.WriteLine("TestDelegate:{0}", stopWatch.Elapsed); stopWatch.Restart();
TestAsycnTask();
stopWatch.Stop();
Debug.WriteLine("TestAsycnTask:{0}", stopWatch.Elapsed); stopWatch.Restart();
TestThreadPools();
stopWatch.Stop();
Debug.WriteLine("TestThreadPools:{0}", stopWatch.Elapsed); stopWatch.Restart();
TestThread();
stopWatch.Stop();
Debug.WriteLine("TestThread:{0}", stopWatch.Elapsed);

(二)测试结果

Delegate、Thread、Task、ThreadPool几种方式创建异步任务性能对比

(三)测试结论

1、线程方式效率是真的低。

2、线程池效率居然比Task还快,不知道为什么,也许测试方式有误。