zoukankan      html  css  js  c++  java
  • 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还快,不知道为什么,也许测试方式有误。

  • 相关阅读:
    可多开窗口,但是不能同一个窗口多标签 keyshot
    AI符号 和 3DS 实例 有点像
    maya 显示 着色
    不懂
    Rhino 图层
    C4D 怎么学了一个多月还什么都不会
    测试音乐文件 wav mp3 mid
    CAD转CDR之类的会断点怎么解决
    javascript
    react脚手架搭建
  • 原文地址:https://www.cnblogs.com/yuekong2010/p/8336676.html
Copyright © 2011-2022 走看看