Home » c# » c# – Which task scheduler is used by default when starting/running/invoking tasks in .NET?-Exceptionshub

c# – Which task scheduler is used by default when starting/running/invoking tasks in .NET?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

Which task scheduler is used when I start tasks from a task that was run with a specific scheduler?

Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.None, new MyTaskScheduler());

// ...

void A()
{
    // 1
    Parallel.Invoke(sometasks);

    // 2
    Task.Run(sometask);

    // 3
    Parallel.For(/*...*/);

    // 4
    // Any other task execution that isn't specifying a scheduler explicitly
}

Do all example will be scheduled by MyTaskScheduler? I want to use the QueuedTaskScheduler (From ParallelExtensionsExtras) to handle priorities and concurrency limitations for complex web api requests (which may start tasks and/or use other TPL functionality).

How to&Answers:

When it comes to most TPL methods, the rule-of-thumb is the default task scheduler is used regardless of which task scheduler is associated with the current thread unless you have explicitly told it otherwise.

You will find most methods will either take options which will have a task scheduler property or you can supply one in the method itself as on overload