欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Task.Factory.StartNew 测试

程序员文章站 2023-10-28 19:18:04
到底该用多少线程?线程数、CPU核心数、本地计算时间、等待时间的关系 线程数 = CPU核心数 * ( 本地计算时间 + 等待时间 ) / 本地计算时间 下面是Task.Factory.StartNew和自己写的TaskHelper.LargeTask.Run对比测试 一、Task.Factory. ......

到底该用多少线程?线程数、cpu核心数、本地计算时间、等待时间的关系 线程数 = cpu核心数 * ( 本地计算时间 + 等待时间 ) / 本地计算时间

下面是task.factory.startnew和自己写的taskhelper.largetask.run对比测试

 

一、task.factory.startnew 使用 taskcreationoptions.longrunning 参数

代码:

private int n = 50000; //问题规模
private int t = 25; //等待时间
private int pagesize = 1000; //打印分页

private void testtaskstartnew()
{
    task.factory.startnew(() =>
    {
        stopwatch stopwatch = stopwatch.startnew();

        list<task> tasklist = new list<task>();
        for (int i = 0; i <= n; i++)
        {
            task task = task.factory.startnew((obj) =>
            {
                thread.sleep(t); //等待时间

                int index = (int)obj;
                if (index % pagesize == 0)
                {
                    this.tryinvoke2(() =>
                    {
                        textbox1.appendtext(index.tostring() + "  ");
                    });
                }
            }, i, taskcreationoptions.longrunning);
            tasklist.add(task);
        }
        task.waitall(tasklist.toarray());

        this.tryinvoke2(() =>
        {
            textbox1.appendtext(string.format("\r\n【task.factory.startnew 问题规模:{0} 等待时间:{1} 耗时:{2}秒】\r\n", n, t, stopwatch.elapsed.totalseconds));
        });
    });
}

private void testtaskhelper()
{
    task.factory.startnew(() =>
    {
        stopwatch stopwatch = stopwatch.startnew();

        list<task> tasklist = new list<task>();
        for (int i = 0; i <= n; i++)
        {
            task task = taskhelper.largetask.run((obj) =>
            {
                thread.sleep(t); //等待时间

                int index = (int)obj;
                if (index % pagesize == 0)
                {
                    this.tryinvoke2(() =>
                    {
                        textbox1.appendtext(index.tostring() + "  ");
                    });
                }
            }, i);
            tasklist.add(task);
        }
        task.waitall(tasklist.toarray());

        this.tryinvoke2(() =>
        {
            textbox1.appendtext(string.format("\r\n【taskhelper.largetask.run {3}线程 问题规模:{0} 等待时间:{1} 耗时:{2}秒】\r\n", n, t, stopwatch.elapsed.totalseconds, taskhelper.largetask.threadcount));
        });
    });
}

测试结果:

0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 11000 12000 13000 14000 15000 16000 17000 18000 19000 20000 21000 22000 23000 24000 25000 26000 27000 28000 29000 30000 31000 32000 33000 34000 35000 36000 37000 38000 39000 40000 41000 42000 43000 44000 45000 46000 47000 48000 49000 50000
【taskhelper.largetask.run 128线程 问题规模:50000 等待时间:25 耗时:10.5975181秒】
0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 11000 12000 13000 14000 15000 16000 17000 18000 19000 20000 21000 22000 23000 24000 25000 26000 27000 28000 29000 30000 31000 32000 33000 34000 35000 36000 37000 38000 39000 40000 41000 42000 43000 44000 45000 46000 47000 48000 49000 50000
【task.factory.startnew 问题规模:50000 等待时间:25 耗时:8.2380754秒】
0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 11000 12000 13000 14000 15000 16000 17000 18000 19000 20000 21000 22000 23000 24000 25000 26000 27000 28000 29000 30000 31000 32000 33000 34000 35000 36000 37000 38000 39000 40000 41000 42000 43000 44000 45000 46000 47000 48000 49000 50000
【taskhelper.largetask.run 128线程 问题规模:50000 等待时间:25 耗时:10.4376939秒】
0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 11000 12000 13000 14000 15000 16000 17000 18000 19000 20000 21000 22000 23000 24000 25000 26000 27000 28000 29000 30000 31000 32000 33000 34000 35000 36000 37000 38000 39000 40000 41000 42000 43000 44000 45000 46000 47000 48000 49000 50000
【task.factory.startnew 问题规模:50000 等待时间:25 耗时:9.2322552秒】

测试结果说明:

我的电脑的cpu是i5-8265u,4核8线程
根据等待时间设置合适的线程数对taskhelper.largetask.run有利
使用taskhelper.largetask.run运行时的cpu占用在5%以下,创建128个线程的瞬间cpu占用达到30%,使用task.factory.startnew运行时的cpu占用接近100%
资源释放情况:task.factory.startnew使用taskcreationoptions.longrunning参数运行完成后线程数立即释放,句柄数未立即释放,而taskhelper.largetask.run提供了手动释放的方法可以立即释放线程数和句柄数,但需要手动调用才能释放

 

 二、task.factory.startnew 不使用 taskcreationoptions.longrunning 参数

代码:

private int n = 2000; //问题规模
private int t = 100; //等待时间
private int pagesize = 100; //打印分页

private void testtaskstartnew()
{
    task.factory.startnew(() =>
    {
        stopwatch stopwatch = stopwatch.startnew();

        list<task> tasklist = new list<task>();
        for (int i = 0; i <= n; i++)
        {
            task task = task.factory.startnew((obj) =>
            {
                thread.sleep(t); //等待时间

                int index = (int)obj;
                if (index % pagesize == 0)
                {
                    this.tryinvoke2(() =>
                    {
                        textbox1.appendtext(index.tostring() + "  ");
                    });
                }
            }, i);
            tasklist.add(task);
        }
        task.waitall(tasklist.toarray());

        this.tryinvoke2(() =>
        {
            textbox1.appendtext(string.format("\r\n【task.factory.startnew 问题规模:{0} 等待时间:{1} 耗时:{2}秒】\r\n", n, t, stopwatch.elapsed.totalseconds));
        });
    });
}

private void testtaskhelper()
{
    task.factory.startnew(() =>
    {
        stopwatch stopwatch = stopwatch.startnew();

        list<task> tasklist = new list<task>();
        for (int i = 0; i <= n; i++)
        {
            task task = taskhelper.largetask.run((obj) =>
            {
                thread.sleep(t); //等待时间

                int index = (int)obj;
                if (index % pagesize == 0)
                {
                    this.tryinvoke2(() =>
                    {
                        textbox1.appendtext(index.tostring() + "  ");
                    });
                }
            }, i);
            tasklist.add(task);
        }
        task.waitall(tasklist.toarray());

        this.tryinvoke2(() =>
        {
            textbox1.appendtext(string.format("\r\n【taskhelper.largetask.run {3}线程 问题规模:{0} 等待时间:{1} 耗时:{2}秒】\r\n", n, t, stopwatch.elapsed.totalseconds, taskhelper.largetask.threadcount));
        });
    });
}

测试结果:

0 100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900 2000
【taskhelper.largetask.run 96线程 问题规模:2000 等待时间:100 耗时:2.1529565秒】
0 2000 100 200 300 400 500 600 700 800 900 1900 1000 1100 1200 1300 1400 1500 1600 1700 1800
【task.factory.startnew 问题规模:2000 等待时间:100 耗时:17.309869秒】
0 100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900 2000
【taskhelper.largetask.run 96线程 问题规模:2000 等待时间:100 耗时:2.143763秒】
0 2000 100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900
【task.factory.startnew 问题规模:2000 等待时间:100 耗时:8.8674353秒】
0 2000 100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900
【task.factory.startnew 问题规模:2000 等待时间:100 耗时:6.5490833秒】
0 2000 100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900
【task.factory.startnew 问题规模:2000 等待时间:100 耗时:5.1381533秒】
0 2000 100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900
【task.factory.startnew 问题规模:2000 等待时间:100 耗时:4.434294秒】
0 2000 100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900
【task.factory.startnew 问题规模:2000 等待时间:100 耗时:4.329009秒】
2000 0 100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900
【task.factory.startnew 问题规模:2000 等待时间:100 耗时:3.6231239秒】
2000 0 100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900
【task.factory.startnew 问题规模:2000 等待时间:100 耗时:3.6303149秒】

测试结论:

task.factory.startnew在不使用taskcreationoptions.longrunning参数时,运行大量耗时任务,线程数增加缓慢,导致需要花费很长时间,如果线程池耗尽,或者线程池未耗尽但有大量耗时任务时,其它任务调用task.factory.startnew会有延迟

我想了一天,多任务还是不要共用线程池比较好,一个任务一个线程池,互不干扰,taskhelper.largetask.run就是按这个思路写的,不知道可有问题

 

附:

limitedtaskscheduler代码:

using system;
using system.collections.concurrent;
using system.collections.generic;
using system.linq;
using system.runtime.interopservices;
using system.text;
using system.threading;
using system.threading.tasks;

namespace utils
{
    public class limitedtaskscheduler : taskscheduler, idisposable
    {
        #region 外部方法
        [dllimport("kernel32.dll", entrypoint = "setprocessworkingsetsize")]
        public static extern int setprocessworkingsetsize(intptr process, int minsize, int maxsize);
        #endregion

        #region 变量属性事件
        private blockingcollection<task> _tasks = new blockingcollection<task>();
        list<thread> _threadlist = new list<thread>();
        private int _threadcount = 0;
        private int _timeout = timeout.infinite;
        private task _temptask;

        public int threadcount
        {
            get
            {
                return _threadcount;
            }
        }
        #endregion

        #region 构造函数
        public limitedtaskscheduler(int threadcount = 10)
        {
            createthreads(threadcount);
        }
        #endregion

        #region override getscheduledtasks
        protected override ienumerable<task> getscheduledtasks()
        {
            return _tasks;
        }
        #endregion

        #region override tryexecutetaskinline
        protected override bool tryexecutetaskinline(task task, bool taskwaspreviouslyqueued)
        {
            return false;
        }
        #endregion

        #region override queuetask
        protected override void queuetask(task task)
        {
            _tasks.add(task);
        }
        #endregion

        #region 资源释放
        /// <summary>
        /// 资源释放
        /// 如果尚有任务在执行,则会在调用此方法的线程上引发system.threading.threadabortexception,请使用task.waitall等待任务执行完毕后,再调用该方法
        /// </summary>
        public void dispose()
        {
            _timeout = 100;

            foreach (thread item in _threadlist)
            {
                item.abort();
            }
            _threadlist.clear();

            gc.collect();
            gc.waitforpendingfinalizers();
            if (environment.osversion.platform == platformid.win32nt)
            {
                setprocessworkingsetsize(system.diagnostics.process.getcurrentprocess().handle, -1, -1);
            }
        }
        #endregion

        #region 创建线程池
        /// <summary>
        /// 创建线程池
        /// </summary>
        private void createthreads(int? threadcount = null)
        {
            if (threadcount != null) _threadcount = threadcount.value;
            _timeout = timeout.infinite;

            for (int i = 0; i < _threadcount; i++)
            {
                thread thread = new thread(new threadstart(() =>
                {
                    task task;
                    while (_tasks.trytake(out task, _timeout))
                    {
                        tryexecutetask(task);
                    }
                }));
                thread.isbackground = true;
                thread.start();
                _threadlist.add(thread);
            }
        }
        #endregion

        #region 全部取消
        /// <summary>
        /// 全部取消
        /// </summary>
        public void cancelall()
        {
            while (_tasks.trytake(out _temptask)) { }
        }
        #endregion

    }
}

taskhelper代码:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;

namespace utils
{
    /// <summary>
    /// task帮助类基类
    /// </summary>
    public class taskhelper
    {
        #region ui任务
        private static limitedtaskscheduler _uitask;
        /// <summary>
        /// ui任务(4个线程)
        /// </summary>
        public static limitedtaskscheduler uitask
        {
            get
            {
                if (_uitask == null) _uitask = new limitedtaskscheduler(4);
                return _uitask;
            }
        }
        #endregion

        #region 计算任务
        private static limitedtaskscheduler _calctask;
        /// <summary>
        /// 计算任务(8个线程)
        /// </summary>
        public static limitedtaskscheduler calctask
        {
            get
            {
                if (_calctask == null) _calctask = new limitedtaskscheduler(8);
                return _calctask;
            }
        }
        #endregion

        #region 网络请求
        private static limitedtaskscheduler _requesttask;
        /// <summary>
        /// 网络请求(32个线程)
        /// </summary>
        public static limitedtaskscheduler requesttask
        {
            get
            {
                if (_requesttask == null) _requesttask = new limitedtaskscheduler(32);
                return _requesttask;
            }
        }
        #endregion

        #region 数据库任务
        private static limitedtaskscheduler _dbtask;
        /// <summary>
        /// 数据库任务(32个线程)
        /// </summary>
        public static limitedtaskscheduler dbtask
        {
            get
            {
                if (_dbtask == null) _dbtask = new limitedtaskscheduler(32);
                return _dbtask;
            }
        }
        #endregion

        #region io任务
        private static limitedtaskscheduler _iotask;
        /// <summary>
        /// io任务(8个线程)
        /// </summary>
        public static limitedtaskscheduler iotask
        {
            get
            {
                if (_iotask == null) _iotask = new limitedtaskscheduler(8);
                return _iotask;
            }
        }
        #endregion

        #region 大线程池任务
        private static limitedtaskscheduler _largetask;
        /// <summary>
        /// 大线程池任务(64个线程)
        /// </summary>
        public static limitedtaskscheduler largetask
        {
            get
            {
                if (_largetask == null) _largetask = new limitedtaskscheduler(128);
                return _largetask;
            }
        }
        #endregion

    }
}