skip to content

In .NET, when should a blocking loop start with Task.Factory.StartNew and TaskCreationOptions.LongRunning rather than Task.Run, and what goes wrong with StartNew?

level: seniorimportance: should knowfreq 45%

answer

  1. dedicated thread outside the pool
  2. only until the first await
  3. Task<Task> needs Unwrap
  4. TaskScheduler.Current, not Default

basics

~20 s

LongRunning suits a loop that blocks for the life of the process: the default scheduler gives it a dedicated thread outside the pool. StartNew's traps: an async lambda loses that thread at its first await and returns Task<Task>, and the scheduler defaults to TaskScheduler.Current.

solid answer

~50 s

`Task.Run` queues to the thread pool, so a loop that blocks forever, such as one reading a blocking device API or draining a `BlockingCollection<T>`, holds a pool thread the pool must replace through its slow injection. `Task.Factory.StartNew(loop, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)` makes the default scheduler start a dedicated background thread named ".NET Long Running Task" instead. Three traps come with StartNew: with an `async` lambda the dedicated thread runs only until the first `await` that does not complete at once, and the rest runs on pool threads; the call returns `Task<Task>`, so you must `Unwrap()` it or await twice; and without a scheduler argument it uses `TaskScheduler.Current`, so called from a task on a custom scheduler it queues there, which can serialise work or deadlock. `Task.Run` always uses `TaskScheduler.Default` and `DenyChildAttach`. LongRunning for short items just buys an expensive new thread each time.

code

csharp · 25 lines
csharp
static string Where() =>
    $"pool={Thread.CurrentThread.IsThreadPoolThread}, name={Thread.CurrentThread.Name}";

// 1. LongRunning on the default scheduler gets a dedicated background thread
await Task.Factory.StartNew(() => Console.WriteLine($"LongRunning:  {Where()}"),
    CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);

// 2. With an async lambda the dedicated thread is gone after the first await
Task<Task> outer = Task.Factory.StartNew(async () =>
{
    Console.WriteLine($"before await: {Where()}");
    await Task.Delay(50);
    Console.WriteLine($"after await:  {Where()}");
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
await outer.Unwrap();   // awaiting outer alone would finish at the first await

// 3. StartNew without a scheduler inherits TaskScheduler.Current
var pair = new ConcurrentExclusiveSchedulerPair();
await Task.Factory.StartNew(() =>
{
    Task viaRun = Task.Run(() => Thread.Sleep(10));
    Task viaStartNew = Task.Factory.StartNew(() => Thread.Sleep(10)); // queued behind this exclusive task
    Console.WriteLine($"Task.Run finished in 1 s:  {viaRun.Wait(1000)}");
    Console.WriteLine($"StartNew finished in 1 s:  {viaStartNew.Wait(1000)}");
}, CancellationToken.None, TaskCreationOptions.None, pair.ExclusiveScheduler);

go deeper

for a junior

Recall that Task.Run uses the thread pool and that LongRunning asks for a separate thread for work that runs a very long time.

for a middle

Explain what the default scheduler does with LongRunning, why an async lambda loses the dedicated thread, and why StartNew with an async lambda returns Task<Task>.

for a senior

Diagnose a StartNew call that inherited TaskScheduler.Current and serialised or deadlocked, and justify when a dedicated thread is cheaper than starving the pool.

for a principal

Make explicit schedulers part of the team's conventions: Task.Run by default, StartNew only with a scheduler argument, and dedicated threads only for a handful of process-lifetime loops.

## What `Task.Run` gives you `Task.Run(action)` is a shortcut. In the runtime source it creates the task with `TaskScheduler.Default` and `TaskCreationOptions.DenyChildAttach`, and the default scheduler queues it to the **thread pool**. That is right for short work items. It is a poor fit for a loop that never returns, because that loop occupies a pool thread for the life of the process, and the pool can only replace it through its throttled injection. Picture the log-ingestion service: one loop reads records from a vendor library whose `Read()` call blocks until data arrives, and hands each record on. That loop runs from start-up to shutdown. ## `LongRunning` on the default scheduler `TaskCreationOptions.LongRunning` is documented as marking a long-running, coarse-grained operation, a hint to the scheduler that oversubscription may be warranted. The **default scheduler** acts on it: its queueing code starts a new **background** thread named `.NET Long Running Task` and runs the task there, outside the pool entirely. The snippet prints `pool=False, name=.NET Long Running Task`. Because it is a hint to the scheduler, a custom `TaskScheduler` may ignore it, so pass `TaskScheduler.Default` explicitly when you mean "dedicated thread". Use it when: - the work **blocks a thread for minutes or for the process lifetime**, - there are **few** such loops (each one is a real OS thread with its own stack), - and the body is **synchronous**. The dedicated thread is a background thread, so it does not keep the process alive; the process can exit while the loop is still inside `Read()`, and your shutdown code decides how the loop is told to stop and whether anyone waits for it. Do not use it for many short items: each task would create and destroy a thread, the cost the pool exists to avoid. ## Trap 1: async lambdas give the thread back at the first `await` An `async` lambda runs synchronously only until its first `await` on something unfinished. At that point it returns a `Task` to StartNew, the dedicated thread's job is over, and the thread exits. The continuation runs wherever the awaited operation completes, normally on a pool thread. The snippet shows `before await: pool=False` and `after await: pool=True, name=.NET TP Worker`. A truly asynchronous loop does not need a dedicated thread at all; plain `Task.Run` or simply calling the async method is enough. ## Trap 2: `Task<Task>` and `Unwrap` `Task.Factory.StartNew(async () => ...)` returns `Task<Task>`: the outer task completes when the lambda **returns its task**, at the first incomplete `await`, not when the work finishes. Awaiting the outer task alone therefore continues almost immediately, and an exception thrown later lands on the inner task where nobody looks. `outer.Unwrap()` (or `await await outer`) gives a task that represents the whole lambda. `Task.Run` has overloads for `Func<Task>` that unwrap for you. ## Trap 3: `TaskScheduler.Current`, not `TaskScheduler.Default` The parameterless `Task.Factory.StartNew(action)` takes its scheduler from the task that is currently running, unless that task was created with `TaskCreationOptions.HideScheduler`; only outside any task does it fall back to `TaskScheduler.Default`. Called from inside a task scheduled on a custom scheduler, the new task queues on that same scheduler. `ConcurrentExclusiveSchedulerPair` makes the danger concrete. Its `ExclusiveScheduler` runs one task at a time. In the snippet, a task on the exclusive scheduler starts one task with `Task.Run` and one with `Task.Factory.StartNew`, then waits for each for a second: the `Task.Run` task finishes, while the StartNew task is still queued behind the very task waiting for it, so the wait times out. With an infinite wait, that is a deadlock. A UI scheduler from `TaskScheduler.FromCurrentSynchronizationContext()` causes the same surprise, moving supposedly background work onto the UI thread. | | `Task.Run(work)` | `Task.Factory.StartNew(work)` | `StartNew(work, ct, LongRunning, TaskScheduler.Default)` | |---|---|---|---| | Scheduler | always `TaskScheduler.Default` | `TaskScheduler.Current` | `TaskScheduler.Default` | | Thread | pool thread | depends on the current scheduler | dedicated background thread | | Async lambda | unwrapped automatically | `Task<Task>` | `Task<Task>`, thread lost at first `await` | | Child attachment | denied | allowed | allowed | ## A short decision list 1. Short CPU or mixed work: `Task.Run`. 2. Asynchronous work: call the async method, or `Task.Run(async () => ...)` to start it off the caller's thread. 3. A synchronous loop that blocks for the life of the process: `Task.Factory.StartNew` with `LongRunning` **and** `TaskScheduler.Default`, or a `Thread` you create yourself. 4. Any other StartNew: always pass the scheduler explicitly.

  • What is .NET's ConcurrentExclusiveSchedulerPair for?
    It provides two coordinated schedulers. Tasks on `ConcurrentScheduler` may run together, up to an optional maximum concurrency, while a task on `ExclusiveScheduler` runs only when nothing else from the pair is running, much like a reader-writer arrangement for tasks. It is useful for serialising access to state without locks, and it is exactly where an unqualified StartNew inherits the exclusive scheduler.
  • Does LongRunning help an async loop that awaits network calls?
    No. The dedicated thread only runs until the loop's first incomplete `await`; after that the loop resumes on pool threads and the dedicated thread exits. An async loop never holds a thread while waiting, so it needs no dedicated thread; start it with `Task.Run` or by calling the async method.
  • What does TaskCreationOptions.HideScheduler change?
    Code running inside a task created with `HideScheduler` sees `TaskScheduler.Default` as `TaskScheduler.Current`, so StartNew calls and continuations created inside it do not inherit the task's custom scheduler. It is a way to protect library code that calls StartNew without a scheduler argument.

Task.Run is a taxi rank: the next free car takes your short trip. LongRunning hires a car with a driver for the whole night, worth it only if you really need the car all night; book the driver for an async trip and he goes home at the first stop while taxis do the rest of the route.

  • Task.Run gives a blocking loop its own dedicated thread automatically
  • LongRunning keeps an async lambda on its dedicated thread across awaits
  • Task.Factory.StartNew always schedules on the thread pool, like Task.Run
  • Awaiting the task from StartNew(async () => ...) waits for the whole lambda
  • Marking every task LongRunning prevents thread pool starvation