Phase 21 of 30 · Topic 21.5

Task Scheduling, `TaskCreationOptions` & Unobserved Exceptions

1Concept

`Task.Run` queues to the default ThreadPool. Long-running tasks should specify `TaskCreationOptions.LongRunning` to instruct the CLR to spawn a dedicated OS thread instead of starving the ThreadPool.

2Architecture Diagram

Short Task (10ms):     Task.Run(...) ──> ThreadPool Worker
Long Task (10 mins):   Task.Factory.StartNew(..., TaskCreationOptions.LongRunning) ──> Dedicated OS Thread

3Code Example

C# 13 & .NET 9
using System;
using System.Threading.Tasks;

public class LongRunningTaskDemo
{
    public static void Main()
    {
        Task longTask = Task.Factory.StartNew(() =>
        {
            Console.WriteLine($"Dedicated OS Background Worker Thread ID: {Environment.CurrentManagedThreadId}");
        }, TaskCreationOptions.LongRunning);

        longTask.Wait();
    }
}

4Expected Output

Dedicated OS Background Worker Thread ID: 9

5Key Takeaways

  • Use `TaskCreationOptions.LongRunning` for continuous message loop listeners.
  • Handle `TaskScheduler.UnobservedTaskException` to log unhandled background exceptions.
  • Never use `Task.Run` to wrap synchronous CPU methods inside library APIs.