Brainbotox · Lessons · Exams

Advanced C# and .NET: Memory, Performance and Concurrency

by lazizanie · Programming · C# / .NET · English

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

GenerationContainsCollected
Gen 0New, short-lived objectsVery often, very fast
Gen 1Survivors of one Gen 0 collection, a buffer zoneOften
Gen 2Long-lived objectsRarely; a full collection is the expensive one
The generational hypothesis: most objects die young. Collecting Gen 0 only examines a small part of the heap, so cheap temporary allocations are fine, while objects that live "just long enough" to reach Gen 2 and then die are the costly ones.

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
}
You almost never need a finalizer. Wrap native handles in a 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

SettingEffect
Workstation GCTuned for low pause times on client machines
Server GCOne heap and one GC thread per core: higher throughput, more memory
Concurrent (background) GCGen 2 collections run mostly while application threads keep working
Calling 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

  1. How does the .NET GC decide that an object is garbage?
  2. From what size is an object allocated on the Large Object Heap?
  3. Why are Gen 0 collections cheap?
  4. What is the effect of a finalizer on an object's lifetime?
  5. What does GC.SuppressFinalize(this) do in Dispose?
  6. Which of these commonly cause memory leaks in managed code?
  7. By default the Large Object Heap is compacted on every Gen 2 collection.
  8. Which GC mode uses one heap per core to maximise throughput on servers?

Take the quiz on Brainbotox

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 string
Span<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
Keep 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

SourceFix
String concatenation in a loopStringBuilder, 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, ToArraySlices of Span
params object[] callsOverloads, 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 a readonly field or an in parameter.
  • 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 = 1 does not compile, because the indexer returns a copy.

Measure, do not guess

Use BenchmarkDotNet with [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

  1. What is Span<T>?
  2. Why can Span<T> not be a field of a class?
  3. Which type should you store in a field or pass across an await to refer to a buffer slice?
  4. What must you remember about an array from ArrayPool<T>.Shared.Rent(1000)?
  5. How do you parse the first four characters of a string as an int without allocating a new string?
  6. What does marking a struct readonly allow the compiler to do?
  7. Which of these allocate on the heap?
  8. A StackOverflowException caused by a huge stackalloc can be caught with try/catch.

Take the quiz on Brainbotox

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.
You cannot 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

TypeUse
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 friendsSnapshots that can be read from any thread
The value factory of 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/O
Use Parallel 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

  1. Why can counter++ from several threads lose updates?
  2. Which object should you lock on?
  3. Which primitive should guard a critical section that contains an await?
  4. What is the fastest correct way to increment a shared int counter?
  5. Declaring a field volatile makes x++ on that field atomic.
  6. What is the standard way to prevent deadlocks when several locks are needed?
  7. What is true of the factory passed to ConcurrentDictionary.GetOrAdd?
  8. Which type gives an async producer/consumer queue with backpressure?

Take the quiz on Brainbotox

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

  1. Local variables become fields of a state machine struct.
  2. Each await becomes: get the awaiter, test IsCompleted.
  3. If the operation is already complete, execution continues synchronously, with no suspension.
  4. 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.
  5. When the operation completes, the continuation calls MoveNext again and the method resumes after the await.
An async method runs synchronously on the caller's thread until its first 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.

A 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 taskWhat you get
await taskThe first inner exception, rethrown with its original stack trace
task.Wait() or task.ResultAn 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 the ExecutionContext.
  • 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.
If a method only passes a task through, with no 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

  1. What does the C# compiler turn an async method into?
  2. What happens when an awaited task is already completed?
  3. What does ConfigureAwait(false) do?
  4. Why does LoadAsync().Result deadlock on a UI thread?
  5. When is ValueTask<T> a better return type than Task<T>?
  6. It is safe to await the same ValueTask twice.
  7. What does task.Wait() throw when the task failed?
  8. Which type lets you wrap a callback-based API as a Task?
  9. ASP.NET Core has a SynchronizationContext that returns continuations to the request thread.

Take the quiz on Brainbotox

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);
Reflection is slow compared with a direct call, bypasses compile-time checks, and does not combine well with trimming and Native AOT, because the linker cannot see which members are used. Cache 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
An 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 boxReplaces
[JsonSerializable] with JsonSerializerContextReflection-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

ReflectionExpression treesSource generators
When it worksRun timeRun timeCompile time
Start-up costHighHigh (compilation)None
Native AOT and trimmingLimitedCompile() falls back to a slow interpreterFully compatible
Errors foundAt run timeAt run timeAt 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

  1. What is the difference between typeof(Customer) and obj.GetType()?
  2. What does an attribute do by itself?
  3. What is an Expression<Func<int, bool>>?
  4. Why does IQueryable<T>.Where take an expression tree and not a delegate?
  5. When does a source generator run?
  6. A source generator can modify the source code you wrote.
  7. Which are drawbacks of heavy reflection use?
  8. What does [GeneratedRegex] give you compared with new Regex(pattern)?

Take the quiz on Brainbotox

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
KindKeywordT appears only asExamples
Covariantout TOutput (return values)IEnumerable<out T>, IReadOnlyList<out T>, Func<out TResult>
Contravariantin TInput (parameters)Action<in T>, IComparer<in T>
InvariantnoneBothList<T>, IList<T>
Variance applies only to generic interfaces and delegates, and only between reference types. 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.

Arrays are covariant for historical reasons, and that is unsafe: 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 and stackalloc.
  • where T : allows ref struct: lets a generic accept types such as Span<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 itself

unsafe 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.

GainsLimits
Very fast start-upNo run-time code generation (Reflection.Emit, dynamic assembly loading)
Lower memory use, small deploymentReflection restricted to what the trimmer can prove is used
No .NET runtime needed on the machineOne build per operating system and architecture
Good fit for containers, serverless, CLI toolsLibraries must be trim and AOT compatible
To prepare a codebase for Native AOT, replace reflection with source generators (JSON, regex, logging, DI) and fix every trim warning reported by the analyzers.

Check yourself

  1. Why is IEnumerable<string> assignable to IEnumerable<object>?
  2. Which keyword marks a contravariant type parameter?
  3. Why is List<T> invariant?
  4. IEnumerable<int> can be assigned to IEnumerable<object> through covariance.
  5. What happens with: object[] a = new string[1]; a[0] = 42;
  6. What do static abstract interface members enable?
  7. What does the fixed statement do in unsafe code?
  8. Which statements about Native AOT are true?
  9. How is a default interface method called on an object of an implementing class that does not override it?

Take the quiz on Brainbotox