到底该用多少线程?线程数、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));
        });
    });
}
View Code

相关文章:

  • 2022-12-23
  • 2022-01-04
  • 2021-06-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-01
  • 2021-08-06
  • 2022-12-23
相关资源
相似解决方案