Advanced C# and .NET: Memory, Performance and Concurrency
Advanced C# for senior developers: garbage collector internals, Span and allocation-free code, thread safety, async internals, reflection, source generators and variance.
Study this lesson with its quizzes on Brainbotox →
.NET memory management and the garbage collector
The .NET garbage collector (GC) is a generational, tracing, compacting collector: it finds the objects still reachable from roots, reclaims the rest, and moves survivors together. Knowing how it works explains most memory and latency problems in .NET applications.
Roots and reachability
An object is alive if it can be reached from a root: a local variable or parameter of a running method, a static field, a GC handle, or the finalization queue. Everything not reachable is garbage. There is no reference counting, so cycles of objects are collected without trouble.
Generations
| Generation | Contains | Collected |
|---|---|---|
| Gen 0 | New, short-lived objects | Very often, very fast |
| Gen 1 | Survivors of one Gen 0 collection, a buffer zone | Often |
| Gen 2 | Long-lived objects | Rarely; a full collection is the expensive one |
The Large Object Heap (LOH)
Objects of 85,000 bytes or more (mostly large arrays and strings) are allocated on the LOH. The LOH is collected only with Gen 2 and is not compacted by default, so it can fragment. Reuse big buffers with ArrayPool<T> instead of allocating new ones.
Finalizers and the Dispose pattern
A finalizer (~MyType()) runs on a dedicated finalizer thread at some unknown time after the object becomes unreachable. An object with a finalizer survives at least one extra collection, because it must stay alive until the finalizer has run.
public sealed class Handle : IDisposable
{
private IntPtr _ptr;
private bool _disposed;
public void Dispose()
{
if (_disposed) return;
Release(_ptr);
_disposed = true;
GC.SuppressFinalize(this); // no need to finalize any more
}
~Handle() => Release(_ptr); // safety net only
}SafeHandle, and implement IDisposable only to forward Dispose to the fields you own.Memory leaks in managed code
A managed leak is an object that is still reachable but no longer needed. The usual causes:
- Static collections or caches that only grow.
- Event subscriptions on long-lived publishers that are never removed.
- Captured variables in long-lived lambdas and timers.
- Undisposed objects holding native memory.
WeakReference<T> refers to an object without keeping it alive, and ConditionalWeakTable attaches data to an object for as long as that object lives.
GC modes
| Setting | Effect |
|---|---|
| Workstation GC | Tuned for low pause times on client machines |
| Server GC | One heap and one GC thread per core: higher throughput, more memory |
| Concurrent (background) GC | Gen 2 collections run mostly while application threads keep working |
GC.Collect() in application code usually hurts: it promotes surviving objects to older generations early and forces an expensive full collection. Measure with a profiler or dotnet-counters first.Check yourself
- How does the .NET GC decide that an object is garbage?
- From what size is an object allocated on the Large Object Heap?
- Why are Gen 0 collections cheap?
- What is the effect of a finalizer on an object's lifetime?
- What does GC.SuppressFinalize(this) do in Dispose?
- Which of these commonly cause memory leaks in managed code?
- By default the Large Object Heap is compacted on every Gen 2 collection.
- Which GC mode uses one heap per core to maximise throughput on servers?
Span, Memory and high-performance C# without allocations
Span<T> is a type-safe view over a contiguous block of memory (an array, a string, stack memory or native memory) that lets you slice and process data without copying or allocating. Fast .NET code is mostly code that allocates less.
Span<T> and ReadOnlySpan<T>
int[] data = { 1, 2, 3, 4, 5, 6 };
Span<int> middle = data.AsSpan(2, 3); // view on 3, 4, 5: no copy
middle[0] = 99; // data[2] is now 99
ReadOnlySpan<char> text = "2026-11-11";
int year = int.Parse(text.Slice(0, 4)); // no Substring, no new stringSpan<T> is a ref struct: it can live only on the stack. It cannot be a field of a class, cannot be boxed, cannot be captured by a lambda, and cannot be kept across an await or a yield.Memory<T>
Memory<T> is the heap-friendly counterpart. It can be stored in a field and passed through async methods, and you call .Span on it when you need to work on the data synchronously.
stackalloc
Span<byte> buffer = stackalloc byte[128]; // on the stack: no GC work at all
stackalloc small and of bounded size, and never use it in a loop with a size that comes from user input: a stack overflow cannot be caught and ends the process.ArrayPool<T>
byte[] rented = ArrayPool<byte>.Shared.Rent(4096);
try
{
int read = stream.Read(rented, 0, 4096);
Process(rented.AsSpan(0, read));
}
finally
{
ArrayPool<byte>.Shared.Return(rented);
}The rented array may be larger than requested and may contain old data, so always track the length you actually use. Never touch an array after returning it.
Where hidden allocations come from
| Source | Fix |
|---|---|
| String concatenation in a loop | StringBuilder, string.Create, interpolated string handlers |
Boxing a struct (to object or a non-generic interface) | Generic APIs and constraints |
| Lambdas that capture variables (closure object and delegate) | static lambdas, pass state as an argument |
| LINQ in hot paths (enumerators, delegates) | A plain loop |
Substring, Split, ToArray | Slices of Span |
params object[] calls | Overloads, or params ReadOnlySpan<T> |
Structs done right
- Mark immutable structs
readonly struct. The compiler can then avoid defensive copies when the struct is accessed through areadonlyfield or aninparameter. - Pass large structs with
in(read-only reference) to avoid copying them. - Keep structs small. A large struct copied on every call is slower than a class.
- A mutable struct in a
List<T>is a trap:list[0].X = 1does not compile, because the indexer returns a copy.
Measure, do not guess
[MemoryDiagnoser] to compare versions in Release mode, and a profiler to find the real hot path. An optimisation without a measurement is a guess.Check yourself
- What is Span<T>?
- Why can Span<T> not be a field of a class?
- Which type should you store in a field or pass across an await to refer to a buffer slice?
- What must you remember about an array from ArrayPool<T>.Shared.Rent(1000)?
- How do you parse the first four characters of a string as an int without allocating a new string?
- What does marking a struct readonly allow the compiler to do?
- Which of these allocate on the heap?
- A StackOverflowException caused by a huge stackalloc can be caught with try/catch.
C# concurrency: threads, locks and thread-safe code
Code is thread-safe when it behaves correctly however the operations of several threads interleave. In C# the tools are, from simplest to most specialised: no shared mutable state, lock, Interlocked, SemaphoreSlim, concurrent collections and channels.
Race conditions
int counter = 0; Parallel.For(0, 1_000_000, _ => counter++); Console.WriteLine(counter); // less than 1,000,000
counter++ is three steps: read, add, write. Two threads can read the same value and both write the same result, losing an update.
lock
private readonly object _gate = new();
private int _counter;
public void Increment()
{
lock (_gate) { _counter++; }
}lock gives mutual exclusion: one thread at a time inside the block. Lock on a private, dedicated object. Never lock on this, a Type or a string, because other code can lock the same object.await inside a lock block (compile error): the continuation may resume on another thread, and a monitor must be released by the thread that took it.Interlocked and volatile
Interlocked.Increment(ref _counter); // atomic, lock-free Interlocked.CompareExchange(ref _state, 1, 0); // set to 1 only if it is 0
Interlocked performs single atomic operations and is faster than a lock for counters and flags. volatile only guarantees that reads see the latest write; it does not make x++ atomic.
SemaphoreSlim: the async-friendly lock
private readonly SemaphoreSlim _sem = new(1, 1);
public async Task UpdateAsync()
{
await _sem.WaitAsync();
try { await SaveAsync(); }
finally { _sem.Release(); }
}With an initial count of N, it also limits concurrency, for example at most 5 simultaneous HTTP calls.
Deadlocks
A deadlock occurs when thread 1 holds lock A and waits for B while thread 2 holds B and waits for A. Prevent it by always taking locks in the same order, holding them briefly, and never calling unknown code (callbacks, events) while holding a lock.
Concurrent collections and channels
| Type | Use |
|---|---|
ConcurrentDictionary<K, V> | Shared lookup table or cache |
ConcurrentQueue<T>, ConcurrentBag<T> | Lock-free producer and consumer collections |
Channel<T> | Async producer/consumer pipeline with optional bounded capacity (backpressure) |
ImmutableList<T> and friends | Snapshots that can be read from any thread |
ConcurrentDictionary.GetOrAdd(key, factory) can run more than once for the same key under contention; only one result is stored. Use Lazy<T> as the value when the factory is expensive or has side effects. Also, each method is atomic alone, but a sequence such as ContainsKey then Add is not.Data parallelism
Parallel.ForEach(images, img => Resize(img)); // CPU-bound
await Parallel.ForEachAsync(urls,
new ParallelOptions { MaxDegreeOfParallelism = 8 },
async (url, ct) => await DownloadAsync(url, ct)); // async I/OParallel and PLINQ for CPU-bound work across cores. For I/O, use async code: blocking thread pool threads on I/O leads to thread pool starvation.Check yourself
- Why can counter++ from several threads lose updates?
- Which object should you lock on?
- Which primitive should guard a critical section that contains an await?
- What is the fastest correct way to increment a shared int counter?
- Declaring a field volatile makes x++ on that field atomic.
- What is the standard way to prevent deadlocks when several locks are needed?
- What is true of the factory passed to ConcurrentDictionary.GetOrAdd?
- Which type gives an async producer/consumer queue with backpressure?
C# async internals: state machines, ConfigureAwait and ValueTask
The compiler rewrites every async method into a state machine whose MoveNext method runs the code between two await points. Understanding that machine explains deadlocks, allocations and where your code resumes.
What the compiler generates
- Local variables become fields of a state machine struct.
- Each
awaitbecomes: get the awaiter, testIsCompleted. - If the operation is already complete, execution continues synchronously, with no suspension.
- Otherwise the state is saved, a continuation is registered with the awaiter, and the method returns an incomplete task to its caller. The state machine is moved to the heap at that moment.
- When the operation completes, the continuation calls
MoveNextagain and the method resumes after theawait.
await of an incomplete operation. async by itself never starts a thread.Where does the continuation run?
By default await captures the current SynchronizationContext (or TaskScheduler) and posts the continuation back to it. In WPF, WinForms and MAUI, that is the UI thread, which is why you can update controls after an await. ASP.NET Core has no synchronization context, so continuations run on any thread pool thread.
The classic deadlock
// UI thread
var text = LoadAsync().Result; // 1. blocks the UI thread
async Task<string> LoadAsync()
{
await Task.Delay(100); // 2. continuation wants the UI thread
return "done"; // 3. never runs: deadlock
}ConfigureAwait(false)
var data = await stream.ReadAsync(buffer).ConfigureAwait(false);
This tells the awaiter not to return to the captured context. Use it in general-purpose library code: it avoids the deadlock above and saves a context switch. In application code that touches the UI after the await, do not use it.
ValueTask
A Task is a heap object. ValueTask<T> is a struct that wraps either a result or a task, so a method that often completes synchronously (a cache hit, buffered data) avoids the allocation.
ValueTask must be consumed once: await it once, do not await it twice, do not call .Result before completion, and do not await it concurrently. If you need any of that, call .AsTask(). When unsure, return Task.Async streams
async IAsyncEnumerable<Order> ReadOrdersAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
await foreach (var row in db.QueryAsync(ct))
yield return Map(row);
}
await foreach (var order in ReadOrdersAsync())
Handle(order);Exceptions and tasks
| How you observe the task | What you get |
|---|---|
await task | The first inner exception, rethrown with its original stack trace |
task.Wait() or task.Result | An AggregateException wrapping the inner exceptions |
await Task.WhenAll(...) | The first exception; all of them are in the Exception property of the WhenAll task |
Other building blocks
TaskCompletionSource<T>creates a task that you complete by hand, to wrap callback-based or event-based APIs.AsyncLocal<T>stores ambient data that flows with the async call chain through theExecutionContext.- Thread pool starvation: blocking calls (
.Result,Thread.Sleep, synchronous I/O) hold pool threads, the pool adds new ones only slowly, and requests queue up. The cure is async all the way.
using or try around it, you can return the task directly without async/await to skip one state machine. Keep async/await when in doubt: it gives correct exception and disposal behaviour.Check yourself
- What does the C# compiler turn an async method into?
- What happens when an awaited task is already completed?
- What does ConfigureAwait(false) do?
- Why does LoadAsync().Result deadlock on a UI thread?
- When is ValueTask<T> a better return type than Task<T>?
- It is safe to await the same ValueTask twice.
- What does task.Wait() throw when the task failed?
- Which type lets you wrap a callback-based API as a Task?
- ASP.NET Core has a SynchronizationContext that returns continuations to the request thread.
Reflection, attributes, expression trees and source generators in C#
Metaprogramming is code that inspects or produces code. C# offers it at run time with reflection and expression trees, and at compile time with source generators. Frameworks such as ASP.NET Core, EF Core and System.Text.Json are built on these tools.
Reflection
Type t = typeof(Customer); // known at compile time
Type u = obj.GetType(); // run-time type of an instance
foreach (PropertyInfo p in t.GetProperties())
Console.WriteLine($"{p.Name}: {p.GetValue(obj)}");
object instance = Activator.CreateInstance(t)!;
MethodInfo m = t.GetMethod("Save")!;
m.Invoke(instance, null);MethodInfo and PropertyInfo objects, or compile them to delegates.Attributes
An attribute attaches metadata to a type or member. It does nothing by itself: some other code (a framework, an analyzer, a generator) reads it and acts.
[AttributeUsage(AttributeTargets.Property)]
public sealed class MaxLengthAttribute : Attribute
{
public int Length { get; }
public MaxLengthAttribute(int length) => Length = length;
}
public class User
{
[MaxLength(50)]
public string Name { get; set; } = "";
}
var attr = typeof(User).GetProperty("Name")!
.GetCustomAttribute<MaxLengthAttribute>();Expression trees
Func<int, bool> del = x => x > 5; // compiled code Expression<Func<int, bool>> expr = x => x > 5; // data describing the code Console.WriteLine(expr.Body); // (x > 5) Func<int, bool> compiled = expr.Compile(); bool ok = compiled(7); // True
Expression<TDelegate> is a tree of objects that describes a lambda. It can be inspected, modified, translated to another language (EF Core turns it into SQL) or compiled into a delegate at run time.This is why IQueryable<T>.Where takes an Expression<Func<T, bool>>, while IEnumerable<T>.Where takes a Func<T, bool>. A method the provider cannot translate causes a run-time error, not a compile error.
Source generators
A source generator is a compiler plug-in that runs during compilation, reads your code through the Roslyn syntax and semantic models, and adds new C# files to the compilation. It can only add code; it cannot rewrite what you wrote, which is why generated members live in partial types.
| Generator in the box | Replaces |
|---|---|
[JsonSerializable] with JsonSerializerContext | Reflection-based JSON serialisation |
[GeneratedRegex("...")] | Building and compiling a Regex at run time |
[LoggerMessage] | Boxing and string formatting in logging calls |
public partial class Validators
{
[GeneratedRegex(@"^\d{4}-\d{2}-\d{2}$")]
private static partial Regex DateRegex();
}Choosing a technique
| Reflection | Expression trees | Source generators | |
|---|---|---|---|
| When it works | Run time | Run time | Compile time |
| Start-up cost | High | High (compilation) | None |
| Native AOT and trimming | Limited | Compile() falls back to a slow interpreter | Fully compatible |
| Errors found | At run time | At run time | At build time |
dynamic
The dynamic keyword defers member lookup to run time through the Dynamic Language Runtime. It is useful for COM interop and loosely shaped data, but you lose compile-time checking and IntelliSense, and errors appear as RuntimeBinderException.
Check yourself
- What is the difference between typeof(Customer) and obj.GetType()?
- What does an attribute do by itself?
- What is an Expression<Func<int, bool>>?
- Why does IQueryable<T>.Where take an expression tree and not a delegate?
- When does a source generator run?
- A source generator can modify the source code you wrote.
- Which are drawbacks of heavy reflection use?
- What does [GeneratedRegex] give you compared with new Regex(pattern)?
Advanced C# type system: variance, generic math and Native AOT
Variance decides when a generic type built on one type argument can be used in place of the same generic type built on another. With static abstract interface members, ref returns and Native AOT, it completes the advanced corner of the C# type system.
Covariance and contravariance
IEnumerable<string> strings = new List<string>(); IEnumerable<object> objects = strings; // covariance: OK Action<object> printAny = o => Console.WriteLine(o); Action<string> printString = printAny; // contravariance: OK List<object> list = new List<string>(); // compile error: List is invariant
| Kind | Keyword | T appears only as | Examples |
|---|---|---|---|
| Covariant | out T | Output (return values) | IEnumerable<out T>, IReadOnlyList<out T>, Func<out TResult> |
| Contravariant | in T | Input (parameters) | Action<in T>, IComparer<in T> |
| Invariant | none | Both | List<T>, IList<T> |
IEnumerable<int> is not an IEnumerable<object>, because that would need boxing.List<T> must be invariant: if a List<string> could be seen as a List<object>, you could call Add(42) on it.
object[] a = new string[1]; a[0] = 42; compiles and throws ArrayTypeMismatchException at run time.Static abstract interface members and generic math
public static T Sum<T>(IEnumerable<T> values) where T : INumber<T>
{
T total = T.Zero;
foreach (T v in values) total += v;
return total;
}
int i = Sum(new[] { 1, 2, 3 });
decimal d = Sum(new[] { 1.5m, 2.5m });An interface can declare static abstract members, including operators. A generic method constrained to that interface can then use +, T.Zero or T.Parse, and the JIT produces specialised code for each value type with no boxing.
More constraints and interface features
where T : unmanaged: T is a value type with no references inside, usable with pointers andstackalloc.where T : allows ref struct: lets a generic accept types such asSpan<T>.- Default interface methods: an interface can supply a method body, so adding a member does not break existing implementers. The default is reachable only through the interface type, not through the class.
- Explicit interface implementation (
void IFoo.Run()) hides a member unless the object is used through that interface, and resolves name clashes between two interfaces.
ref returns, ref locals and unsafe code
public ref int Find(int[] data, int value)
{
for (int i = 0; i < data.Length; i++)
if (data[i] == value) return ref data[i];
throw new InvalidOperationException();
}
ref int slot = ref Find(numbers, 7);
slot = 70; // writes into the array itselfunsafe code allows pointers and requires the AllowUnsafeBlocks option. The fixed statement pins an object so the GC does not move it while a pointer refers to it. In most cases Span<T> gives the same speed with safety checks.
Native AOT
Native AOT compiles the application ahead of time to a self-contained native executable. There is no JIT and no IL at run time.
| Gains | Limits |
|---|---|
| Very fast start-up | No run-time code generation (Reflection.Emit, dynamic assembly loading) |
| Lower memory use, small deployment | Reflection restricted to what the trimmer can prove is used |
| No .NET runtime needed on the machine | One build per operating system and architecture |
| Good fit for containers, serverless, CLI tools | Libraries must be trim and AOT compatible |
Check yourself
- Why is IEnumerable<string> assignable to IEnumerable<object>?
- Which keyword marks a contravariant type parameter?
- Why is List<T> invariant?
- IEnumerable<int> can be assigned to IEnumerable<object> through covariance.
- What happens with: object[] a = new string[1]; a[0] = 42;
- What do static abstract interface members enable?
- What does the fixed statement do in unsafe code?
- Which statements about Native AOT are true?
- How is a default interface method called on an object of an implementing class that does not override it?