skip to content

.NET

The cross-platform .NET runtime under C# services: the CLR and JIT, garbage collection, the thread pool, core library services and hosting. Interviewers check what runs below the framework.

on this pageshow

explore

questions

page 1 of 2

In .NET, what runs the delegate you pass to Task.Run, and how does a thread pool thread differ from one created with new Thread?

level: juniorimportance: must knowfreq 62%

answer

  1. one shared pool per process
  2. threads reused, not created per call
  3. background vs foreground
  4. minimum tied to processor count

basics

~20 s

Task.Run queues the delegate to the process's single managed thread pool, where a reused worker thread runs it. Pool threads are background threads the runtime creates and retires itself; new Thread gives you a dedicated foreground thread that you own.

solid answer

~50 s

`Task.Run` hands the delegate to `TaskScheduler.Default`, which queues it as a work item on the process's one managed thread pool; whichever worker thread is free picks it up, and the same threads also run timer callbacks, most `await` continuations and other tasks. Pool threads are **background** threads, so the process exits without waiting for them. The pool creates worker threads on demand without delay up to a minimum of `Environment.ProcessorCount`; above that it adds threads only through its own throttled algorithm, and idle ones exit after a while. `new Thread` creates a dedicated thread, foreground by default, that keeps the process alive until it finishes. The docs reserve that for work that needs a foreground thread, a particular priority, a stable identity or a long block, and it costs a new thread and stack every time.

code

csharp · 23 lines
csharp
ThreadPool.GetMinThreads(out int minWorkers, out _);
Console.WriteLine($"ProcessorCount={Environment.ProcessorCount}, min worker threads={minWorkers}");

await Task.Run(() =>
{
    Thread t = Thread.CurrentThread;
    Console.WriteLine($"Task.Run: pool={t.IsThreadPoolThread}, background={t.IsBackground}");
});

ThreadPool.QueueUserWorkItem(_ =>
{
    Thread.Sleep(2000);
    Console.WriteLine("pool item done"); // never printed
});

var own = new Thread(() =>
{
    Thread.Sleep(500);
    Console.WriteLine("own thread done"); // printed: foreground keeps the process alive
});
Console.WriteLine($"new Thread: background={own.IsBackground}");
own.Start();
Console.WriteLine("top-level code returns");

go deeper

for a junior

Recall that Task.Run queues to the shared thread pool, that pool threads are background threads that get reused, and that new Thread is a foreground thread you own.

for a middle

Explain the minimum worker count equal to the processor count, what creates threads above it, and why queued work waits when every worker is busy.

for a senior

Show you know what else shares the pool, timers and await continuations included, and why long blocking work belongs on its own thread rather than a pool thread.

for a principal

Frame the pool as a process-wide shared resource: any library that blocks its threads slows every other component, so the rules for what may run on it apply to the whole codebase.

## What `Task.Run` actually does `Task.Run(action)` does not create a thread. It builds a `Task` and gives it to `TaskScheduler.Default`, the scheduler that sits on top of the **managed thread pool**. The scheduler queues the task as a **work item**, and the next free **worker thread** takes it off the queue and runs the delegate. When the delegate returns, that thread goes back to the pool and picks up the next work item, which may belong to completely unrelated code. Picture a nightly job that resizes product images. If it calls `Task.Run(() => Resize(path))` for a batch of files, the resize calls share a few pool threads; the job never owns any of them. ## One pool per process, shared by everything - **There is exactly one thread pool per process.** Your code, the base libraries and any library you reference all queue to it. - **It runs more than `Task.Run`.** The .NET docs list Task Parallel Library operations, asynchronous I/O completion, timer callbacks and registered waits among its users. The code after an `await` in a console app usually resumes as a pool work item too. - **Threads are reused.** Creating an OS thread and its stack is expensive; reusing a warm thread is cheap, which is the whole point of the pool. - **Idle threads retire.** In the runtime source, an idle worker exits after 20 seconds without work by default (`System.Threading.ThreadPool.ThreadTimeoutMs`). - **Queuing is unbounded.** The docs state that the number of queued work items is limited only by memory; when every worker is busy, new items wait. ## Background versus foreground The runtime keeps a process alive while at least one **foreground** thread runs. **Background** threads do not count: when the last foreground thread ends, the runtime stops them without raising an exception in them, so they never get to finish or clean up. | | Thread pool thread (`Task.Run`, `QueueUserWorkItem`) | `new Thread(...)` | |---|---|---| | Who creates it | the runtime, on demand | your code, every time | | `IsBackground` | `true` | `false` unless you set it | | Keeps the process alive | no | yes, until it finishes | | Reused for other work | yes | no, it ends with its delegate | | Name, priority, identity | shared and transient | yours to set and keep | The snippet below shows the difference: the pool work item that sleeps for two seconds never prints, because top-level code returns and only the foreground thread is waited for. ## How many threads the pool has `ThreadPool.GetMinThreads` reports a minimum worker count equal to `Environment.ProcessorCount` by default (14 on the machine the snippet ran on). That number is not a pool that sits full: the docs note the actual count can fall below the minimum when demand is low. It is the point up to which the pool **creates threads on demand without delay**. Above it, the pool grows through its own throttled logic (hill climbing, a starvation check and, for threads blocked waiting on a task, a faster compensation path), which is why code that blocks pool threads gets slow. The ceiling, from `ThreadPool.GetMaxThreads`, is 32,767 worker threads on 64-bit builds. The minimum can be raised with `ThreadPool.SetMinThreads`, the `System.Threading.ThreadPool.MinThreads` runtime setting or the `ThreadPoolMinThreads` project property, though the docs warn that raising it unnecessarily can hurt. ## Exceptions on pool threads An unhandled exception thrown by a `ThreadPool.QueueUserWorkItem` callback terminates the process, just as it would on any thread. `Task.Run` behaves differently because the `Task` catches the exception and stores it; it reappears when someone awaits the task or calls `Wait` or `Result`. That is a property of `Task`, not of the pool. ## When to use your own thread The thread pool docs name the cases where a dedicated thread is the better tool: 1. You need a **foreground** thread that keeps the process running. 2. You need a particular **priority**. 3. The work **blocks for long periods**, which would tie up pool threads and stop other work items from starting. 4. You need a single-threaded apartment (pool threads are multithreaded-apartment threads, a Windows COM concern). 5. You need a **stable identity**, or a thread dedicated to one task. For short, independent pieces of work, `Task.Run` and the pool are the default; a hand-made `Thread` per item would pay thread-creation cost every time and leave the process waiting on threads you forgot about.

  • What happens to work still running on the thread pool when a .NET console app's top-level code returns?
    Pool threads are background threads, so once the last foreground thread ends the runtime stops them and the process exits. No exception is raised in them, so the work item gets no chance to finish or clean up. Work that must complete has to be awaited (or waited on) before returning, or run on a foreground thread.
  • Why does an unhandled exception in a ThreadPool.QueueUserWorkItem callback end the process, while the same exception inside Task.Run does not?
    An unhandled exception on any thread, pool threads included, terminates the process. `Task.Run` wraps the delegate in a `Task`, which catches the exception and stores it on the task; it is rethrown to whoever awaits it or calls `Wait`, `Result` or `GetAwaiter().GetResult()`. `QueueUserWorkItem` has no task to store it in.

  • Task.Run always creates a brand-new thread for its delegate
  • Thread pool threads are foreground, so the process waits for them
  • The pool always holds exactly ProcessorCount threads and never grows
  • A new Thread per small work item is cheaper than queuing to the pool
  • Exceptions in QueueUserWorkItem callbacks are silently swallowed by the pool
open as a page

In .NET, why should an invoicing service record payment and due instants as DateTimeOffset rather than DateTime, and what does DateTime.Kind fail to capture?

level: juniorimportance: must knowfreq 62%

basics

~20 s

A DateTime carries only a Kind flag (Utc, Local or Unspecified), and equality ignores it, so values from different zones mix silently. DateTimeOffset stores the UTC offset and compares by instant, though an offset is not a time zone.

open as a page

In .NET, what does the C# compiler put into an assembly, and when does the JIT turn a method into machine code?

level: juniorimportance: must knowfreq 65%

basics

~20 s

The C# compiler emits IL, a CPU-independent instruction set, plus metadata describing every type, member signature and reference. At run time the JIT compiles each method to native code on its first call, and later calls in that process reuse it.

open as a page

In .NET, what are garbage-collection generations 0, 1 and 2, and how does an object move from one to the next?

level: juniorimportance: must knowfreq 75%

basics

~20 s

The .NET GC puts new small objects in gen 0; an object that survives a gen 0 collection is promoted to gen 1, and one that survives a gen 1 collection to gen 2, which only a full (gen 2) collection reclaims.

open as a page

In .NET, how do Parallel.ForEach and Parallel.ForEachAsync differ for an image-resizing job, including each one's default degree of parallelism?

level: middleimportance: must knowfreq 55%

basics

~20 s

Parallel.ForEach blocks the caller, runs an Action<T> per item on pool threads plus the calling thread, and sets no upper bound on parallelism by default. Parallel.ForEachAsync (.NET 6) returns a Task, awaits a ValueTask-returning body and defaults to Environment.ProcessorCount.

open as a page

With System.Text.Json's JsonSerializer, which naming and case-sensitivity defaults apply, and why should code reuse one JsonSerializerOptions instance?

level: middleimportance: must knowfreq 52%

basics

~20 s

JsonSerializer writes property names exactly as declared and matches them case-sensitively on read, silently skipping unmatched JSON. Each JsonSerializerOptions instance caches per-type metadata and becomes read-only after first use, so create one and share it.

open as a page

In .NET 10, how does tiered compilation move a method from quick JIT to optimized code, and why are a service's first requests slower?

level: middleimportance: must knowfreq 55%

basics

~20 s

Methods start on quick tier-0 code or their ReadyToRun code; hot ones, after 30 calls once startup quiets, are recompiled in the background at tier 1 using dynamic PGO data. Early requests pay for JIT and run the slower first-tier code.

open as a page

In .NET, what triggers a gen 2 collection, and why does a service that churns 200 KB arrays see so many of them?

level: middleimportance: must knowfreq 60%

basics

~20 s

A .NET gen 2 collection starts when gen 2's or the large object heap's allocation budget runs out, when memory is low, or when code calls GC.Collect. Arrays of 85,000 bytes or more go to the LOH, so churning them triggers full collections.

open as a page

In .NET 10, how do workstation GC, server GC and DATAS differ, and which does a console or ASP.NET Core app get by default?

level: middleimportance: must knowfreq 65%

basics

~20 s

Workstation GC uses one heap and collects on the allocating thread; server GC collects up to one heap per logical CPU on dedicated threads. Console apps default to workstation, ASP.NET Core apps to server, whose heap count DATAS has adapted since .NET 9.

open as a page

Why does the .NET thread pool add threads so slowly when a nightly image job's 64 work items each block on a synchronous upload, and what changes that?

level: seniorimportance: must knowfreq 58%

basics

~20 s

The pool creates threads on demand only up to its minimum, Environment.ProcessorCount; above it, a starvation check adds about one thread per half second for stuck work. Task.Wait-style blocking gets faster compensation. The fix is to stop blocking pool threads.

open as a page

What does `dotnet new worker` generate in .NET 10, and how does a Worker Service project differ from a plain console app?

level: juniorimportance: should knowfreq 40%

basics

~10 s

A Worker Service is a console executable that boots the .NET generic host: Program.cs calls Host.CreateApplicationBuilder, registers a Worker class with AddHostedService and runs the host, in a project built on the Microsoft.NET.Sdk.Worker SDK.

open as a page

In .NET, why does timing a method with a Stopwatch loop give misleading numbers, and what does BenchmarkDotNet do instead?

level: juniorimportance: should knowfreq 42%

basics

~20 s

A Stopwatch loop folds JIT compilation, tier changes, collections and noise into one number, and an unused result may be optimized away. BenchmarkDotNet runs a Release build in its own process, warms up, subtracts its overhead and reports statistics.

open as a page

In .NET's PLINQ, what does AsParallel() change about the order of query results, and when is a PLINQ query slower than plain LINQ?

level: middleimportance: should knowfreq 34%

basics

~20 s

AsParallel() drops the guarantee that results come back in source order; AsOrdered() or OrderBy restores it at a cost. PLINQ is slower than plain LINQ when each element's work is too cheap to pay for partitioning, coordinating threads and merging results.

open as a page

In .NET, why can Stream.Read(buffer, 0, 8) return fewer than 8 bytes before the stream ends, and how do ReadExactly and ReadAtLeast fix header parsing?

level: middleimportance: should knowfreq 36%

basics

~20 s

Stream.Read only promises between one byte and the count requested, or zero at end of stream; pipes, sockets and compression streams return what is available. ReadExactly fills the buffer or throws EndOfStreamException; ReadAtLeast guarantees a minimum.

open as a page

In a .NET library project, what changes between targeting netstandard2.0, net10.0 and net10.0-windows, and how do OperatingSystem.IsWindows() and CA1416 guard Windows-only calls?

level: middleimportance: should knowfreq 38%

basics

~20 s

The target framework fixes the API surface you compile against: netstandard2.0 also reaches .NET Framework but lacks newer APIs, net10.0 exposes the full cross-platform library, and net10.0-windows marks the assembly Windows-only. CA1416 flags platform-specific calls unless guarded by OperatingSystem.IsWindows().

open as a page

For a .NET 10 command-line tool, what does ReadyToRun change at startup compared with Native AOT, and what does each give up?

level: middleimportance: should knowfreq 50%

basics

~20 s

ReadyToRun ships precompiled code beside the IL, so less is jitted at startup, but the JIT stays and re-jits hot methods. Native AOT has no JIT: faster startup, less memory, but trimming, per-platform binaries and no run-time code generation or assembly loading.

open as a page

In .NET 10, how do Host.CreateApplicationBuilder and Host.CreateDefaultBuilder differ, and which defaults do both apply?

level: middleimportance: should knowfreq 38%

basics

~20 s

CreateApplicationBuilder returns a HostApplicationBuilder whose Configuration, Services and Logging you change directly; CreateDefaultBuilder returns an IHostBuilder that queues callbacks until Build. Both apply the same defaults for content root, configuration, logging, DI validation and lifetime.

open as a page

In a .NET console tool, how do you wire Microsoft.Extensions configuration, logging and DI without the generic host, and what do you give up?

level: middleimportance: should knowfreq 30%

basics

~10 s

Build an IConfiguration with ConfigurationBuilder, register services and AddLogging on a ServiceCollection, then build and dispose the ServiceProvider. You give up environments, user secrets, default providers, Development validation, hosted services and Ctrl+C handling.

open as a page

A .NET console import tool built on Host.CreateApplicationBuilder finishes its work in a hosted service but never exits; why, and how should it be structured?

level: middleimportance: should knowfreq 28%

basics

~20 s

host.Run() blocks until shutdown is triggered, which the default ConsoleLifetime does only on Ctrl+C, SIGQUIT or SIGTERM; a finished hosted service stops nothing. A one-shot tool builds the host, resolves its service, awaits it and returns an exit code.

open as a page

In BenchmarkDotNet, how do Baseline = true, [MemoryDiagnoser] and [Params] show that a rewritten CSV tokenizer is faster and allocates less?

level: middleimportance: should knowfreq 38%

basics

~20 s

Mark the old tokenizer [Benchmark(Baseline = true)] so each row gets a Ratio against it, add [MemoryDiagnoser] for Allocated bytes and Gen 0/1/2 collections per 1,000 operations, and use [Params] to repeat both for several input sizes.

open as a page

Using dotnet-counters on a .NET 10 process at 90% CPU with climbing memory, which System.Runtime counters do you read first, and why?

level: middleimportance: should knowfreq 36%

basics

~20 s

Run dotnet-counters monitor -p <pid> --showDeltas; it shows the System.Runtime meter by default. Compare CPU time with GC pause time and collections, the allocation total's growth, heap size against working set, the thread pool queue and exceptions.

open as a page

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%

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.

open as a page

With System.Text.Json in .NET 10, why does serializing a Document[] holding Invoice and CreditNote objects drop derived properties, and how do [JsonDerivedType] and a JsonSerializerContext fix it under Native AOT?

level: seniorimportance: should knowfreq 32%

basics

~20 s

JsonSerializer uses the declared element type, so a Document[] writes only Document's members. [JsonDerivedType] on the base adds a $type discriminator and round-trips the subclasses; a JsonSerializerContext generates those contracts at compile time, which Native AOT requires.

open as a page

A .NET 10 invoice-number Regex pins a request thread on crafted input; what do match timeouts, RegexOptions.NonBacktracking and [GeneratedRegex] each change?

level: seniorimportance: should knowfreq 30%

basics

~20 s

The default .NET Regex engine backtracks and has no timeout (Regex.InfiniteMatchTimeout), so a nested quantifier can run for a very long time. A matchTimeout throws RegexMatchTimeoutException; NonBacktracking matches in linear time; [GeneratedRegex] moves construction to build time but keeps backtracking.

open as a page

A .NET desktop host loads customer plugins into a collectible AssemblyLoadContext and calls Unload, yet the plugins never leave memory; why, and how do you prove it?

level: seniorimportance: should knowfreq 28%

basics

~20 s

AssemblyLoadContext.Unload only starts a cooperative unload; the context is freed once nothing references it or anything loaded in it. A cached plugin object, Type, delegate, event handler or running thread keeps it alive; a WeakReference checked after forced collections proves it.

open as a page

A .NET 10 order-matching service in a 2 GiB container has p99 latency spikes that line up with gen 2 collections; how do you find the cause and fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Classify the gen 2 collections and find their trigger with GC.GetGCMemoryInfo and GC.CollectionCount: LOH churn, a heap near the container's default 75% limit, GC.Collect calls or gen 2 growth. Remove that trigger before tuning GC settings.

open as a page

Why does a .NET object with a finalizer survive at least one garbage collection longer than the same object without one, and what does that cost?

level: seniorimportance: should knowfreq 35%

basics

~20 s

When the .NET GC finds a finalizable object unreachable, it cannot free it: it queues the object for the finalizer thread, so the object and everything it references survive that collection and are promoted. Only a later collection reclaims them.

open as a page

A .NET 10 worker running as a Windows Service loads appsettings.json, yet File.ReadAllText("tariffs.csv") looks in C:\Windows\system32; why, and how do you fix it?

level: seniorimportance: should knowfreq 26%

basics

~20 s

Windows Services start with C:\Windows\system32 as current directory. The generic host detects that and uses AppContext.BaseDirectory as content root, so appsettings.json loads, but File APIs still resolve relative paths against the current directory. Build paths from IHostEnvironment.ContentRootPath.

open as a page

A .NET 10 service sits at 90% CPU in production; how do you capture and read a CPU profile with dotnet-trace, and what are its limits?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Run dotnet-trace collect -p <pid> --duration for a short window; it enables the dotnet-common and dotnet-sampled-thread-time profiles over EventPipe. Open the nettrace in PerfView or Visual Studio on Windows, or convert it to Speedscope, and read the hottest stacks.

open as a page

A .NET service's memory climbs for an hour; when do you take a dotnet-gcdump, when a dotnet-dump, and how do you find what keeps objects alive?

level: seniorimportance: should knowfreq 33%

basics

~20 s

dotnet-gcdump captures the managed object graph over EventPipe but forces a full gen 2 collection; dotnet-dump writes a process dump analyzed with SOS. Compare type counts between two snapshots, then run gcroot on an instance of the growing type.

open as a page

showing 1–30 of 36