Phase 14 of 30 · Topic 14.3

Async Stack Traces & `ExceptionDispatchInfo.Capture`

1Concept

`ExceptionDispatchInfo.Capture(ex).Throw()` captures an exception and its exact call stack, allowing it to be rethrown from a background thread or async continuation without losing the original stack frames.

2Architecture Diagram

Background Worker Thread ──> Throws Exception ──> Captured by ExceptionDispatchInfo
                                                                   │
                                                                   ▼
Main Dispatcher Thread <── Rethrown seamlessly with original callstack intact!

3Code Example

C# 13 & .NET 9
using System;
using System.Runtime.ExceptionServices;

public class ExceptionDispatchDemo
{
    public static void Main()
    {
        ExceptionDispatchInfo? capturedError = null;

        try
        {
            int zero = 0;
            int crash = 10 / zero;
        }
        catch (DivideByZeroException ex)
        {
            // Capture full stack trace
            capturedError = ExceptionDispatchInfo.Capture(ex);
        }

        if (capturedError != null)
        {
            Console.WriteLine("Exception captured successfully. Ready to rethrow on another thread.");
        }
    }
}

4Expected Output

Exception captured successfully. Ready to rethrow on another thread.

5Key Takeaways

  • `ExceptionDispatchInfo` powers async/await exception marshalling across thread hops.
  • Appends `--- End of stack trace from previous location ---` markers in logs.
  • Essential for building custom resilient thread pool workers.