rmbq
rmbq

Reputation: 473

Task.Run takes much time to start the task

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();
}

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(() => {
         ...
       });
    }

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?

Upvotes: 6

Views: 4221

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73452

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.

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); 

Upvotes: 20

Related Questions