Task.Run 需要很多时间来启动任务 [英] Task.Run takes much time to start the task

查看:67
本文介绍了Task.Run 需要很多时间来启动任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我有 ~40 个正在运行的任务,定义如下:

In my program i have ~40 running task, defined like:

private void StartTryReconnectTask() {
       TryReconnectCTKS = new CancellationTokenSource();
       TryReconnectTask = new Task(this.TryReconnect, TryReconnectCTKS.Token);
       TryReconnectTask.Start();
}

在 TryReconnect() 内部有一个无限的 while 循环,只有在任务被取消时才会停止.我觉得这里一切都很好.

Inside TryReconnect() there is an infinite while loop that stops only when the task is cancelled. everything seems fine to me here.

然后我需要点击按钮开始一个任务(不是无限的):

Then i need to start a task (not infinite) on a button click:

private void ExecuteRepairCommand(object o) {
       Task.Run(() => {
         ...
       });
    }

开始这项新任务需要大约 30/40 秒.如果我使用线程一切正常,线程会立即启动.为什么?什么原因?

it take ~30/40 seconds to start this new task. if i use thread everything works correctly, the thread starts instantly. why? what's the cause?

推荐答案

默认情况下,任务被调度到 ThreadPool.当您安排大量任务时,ThreadPool 不会创建新线程.它会在创建新线程之前等待一段时间(基于一些启发式).这就是您注意到任务开始延迟的原因.我已经在这里解释过.

By default tasks are scheduled to ThreadPool. ThreadPool won't create new threads when you schedule lot of tasks. It will wait for sometime before creating new threads(based on some heuristics). That's why you notice a delay in starting of your tasks. I've explained it earlier here.

回到你的问题.如果你的任务需要长时间运行,你真的应该考虑使用 LongRunning 标志.它会指示任务调度器给它一个新线程;让你的任务可以独立运行很长时间,不影响其他任务.

Back to your question. If your task is long running, you should really consider using LongRunning flag. It will instruct the Task Scheduler to give it a new thread; so your task can run independently for a long time without affecting other tasks.

Task.Factory.StartNew(() =>
{
    ...
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); 

这篇关于Task.Run 需要很多时间来启动任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆