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还快,不知道为什么,也许测试方式有误。

  • 相关阅读:
    github克隆镜像
    python2安装pip(get-pip.py)和pip更新源
    GitHack使用—create_unverified_context报错
    XCTF:shrine(Flask模块注入)
    开机自启动(C#)
    操作xml(C#)
    隐藏到托盘(C#)
    火狐浏览器下请求两次(C#)
    Nancy学习笔记
    jquery纵向抽屉式导航栏
  • 原文地址:https://www.cnblogs.com/yuekong2010/p/8336676.html
Copyright © 2011-2022 走看看