## Executive Summary

In this landmark systems-level session, Rich Lander and Andy Gocke reveal two monumental architectural evolutions arriving in the .NET runtime:
1. **Runtime Async:** A fundamental redesign of asynchronous execution in .NET. After 15 years of compiler-generated Roslyn state machines (`IAsyncStateMachine`), .NET 11 moves async suspension and resumption directly into the CoreCLR runtime and JIT compiler. By introducing a new machine-level calling convention and JIT intrinsics, async methods that complete synchronously achieve **0 bytes allocated across any stack depth** (down from hundreds of bytes per frame), cut call-chain execution times by up to **13%**, clean up call stacks completely, and deliver **2.5x to 3.4x faster exception handling** during failure storms.
2. **Memory Safety V2:** Formalizing C#'s memory safety contracts to establish parity with Rust and Swift (2025 model). While C# has been memory-safe by default since 1.0, escape hatches (`unsafe`, raw pointers, native interop) lacked enforceable caller obligations. Memory Safety V2 introduces an explicit contract and blame system, XML `<safety>` requirements, unifies unsafe field obligations, and introduces **unsafe expressions** (`unsafe(...)`) for ergonomic, zero-overhead safety encapsulation.

![Session Title Slide](/dotnetconf2026/archive/16-runtime-vnext-memory-safety-async/screenshots/01_title_runtime_vnext.webp)

---

## Architecture: Compiler Async vs. Runtime Async

```mermaid
graph TD
    subgraph "Legacy Compiler Async (Roslyn State Machine)"
        C_SRC["C# async Task Method"] --> C_ROS["Roslyn Compiler Transformation"]
        C_ROS --> C_SM["Emit Hidden Struct/Class<br/>&lt;Method&gt;d__0 : IAsyncStateMachine"]
        C_SM --> C_BLD["AsyncTaskMethodBuilder&lt;T&gt;"]
        C_BLD --> C_HEAP["Task Object Heap Allocation (216B - 504B+)"]
        C_SM --> C_IND["Method-by-Method Isolation<br/>(No Interprocedural Optimization)"]
    end

    subgraph "Runtime Async vNext (CoreCLR & JIT)"
        R_SRC["C# async Task Method<br/>(Zero Source Code Changes)"] --> R_ROS["Roslyn Compiler (Lightweight IL)"]
        R_ROS --> R_ATTR["[MethodImpl(MethodImplOptions.Async)]<br/>AsyncHelpers.Await() JIT Intrinsic"]
        R_ATTR --> R_JIT["JIT Compiler & New Async Calling Convention"]
        R_JIT --> R_IPO["Interprocedural Optimization (IPO)<br/>Optimizes entire call chain as a whole"]
        R_IPO --> R_ZERO["Sync Path: 0 Bytes Allocated<br/>Clean Stack Traces & Fast Exception Handling"]
    end
```

---

## 1. Runtime Async: Making Async Code Cheaper

### The Problem with 15 Years of Compiler Async
Since C# 5.0 (2012), `async`/`await` has transformed non-blocking I/O. However, because async was implemented entirely within the Roslyn C# compiler, it transformed simple methods into complex IL state machines:
* **Code Bloat:** Even a one-line method like `await Task.Delay(1)` generates dozens of lines of IL, allocating compiler-generated classes (`<Main>d__0`), state integer tracking, and builder scaffolding.
* **"Trees vs. Forest" Optimization Barrier:** Roslyn operates on one method at a time. The JIT compiler cannot "see through" state machine bounds across multiple call frames, blocking inlining and cross-method optimizations.
* **Synchronous Completion Tax:** Real-world async code frequently completes synchronously (e.g. reading from an in-memory stream, populated cache, or pre-buffered socket). Despite completing immediately, traditional async still incurs state machine overhead and task allocations across the call chain.

![Compiler Async State Machine Bloat](/dotnetconf2026/archive/16-runtime-vnext-memory-safety-async/screenshots/03_compiler_async_state_machine_bloat.webp)

### The .NET 11 Solution: JIT Intrinsics & New Calling Convention
Runtime Async shifts state machine orchestration from compile-time IL to runtime JIT intrinsics:

![Runtime Async JIT Intrinsic](/dotnetconf2026/archive/16-runtime-vnext-memory-safety-async/screenshots/04_runtime_async_jit_intrinsic.webp)

```csharp
// How Roslyn lowers C# with Runtime Async enabled:
internal class Program
{
    [MethodImpl(MethodImplOptions.Async)] // New machine-level calling convention
    [NullableContext(1)]
    private static Task Main() =>
        AsyncHelpers.Await(Task.Delay(1)); // JIT Intrinsic (handled in CoreCLR engine)
}
```

* **`MethodImplOptions.Async`:** Introduces a low-level calling convention at the native machine assembly level that CoreCLR recognizes.
* **`AsyncHelpers.Await()`:** A JIT intrinsic that serves as a direct handshake with the runtime JIT. It generates no BCL code; the JIT synthesizes native suspension/resumption code directly.

### Configuration & Adoption Roadmap
Runtime Async is available in .NET 11 as an opt-in feature, and will become the default in .NET 12:

```xml
<PropertyGroup>
    <Features>runtime-async=on</Features>
    <!-- Or via MSBuild property: -->
    <!-- <RuntimeAsync>true</RuntimeAsync> -->
</PropertyGroup>
```

> [!NOTE]
> Large parts of the .NET 11 BCL and ASP.NET Core framework libraries were already compiled with Runtime Async enabled out-of-the-box, providing performance gains even before end-user projects opt in.

![Runtime Async Opt-in Configuration](/dotnetconf2026/archive/16-runtime-vnext-memory-safety-async/screenshots/02_runtime_async_optin.webp)

---

## 2. Performance & Allocation Benchmarks

### 0-Byte Allocations on Synchronous Completion Paths
Through **Interprocedural Optimization (IPO)**, the JIT evaluates the entire async call chain together. When operations complete synchronously, the task allocations across all frames are completely eliminated:

| Call Chain Depth | Legacy Compiler Async Allocation | Runtime Async Allocation | Savings |
|---|---|---|---|
| **3 Frames** | 216 Bytes | **0 Bytes** | **-100%** |
| **5 Frames** | 360 Bytes | **0 Bytes** | **-100%** |
| **7 Frames** | 504 Bytes | **0 Bytes** | **-100%** |
| **32 Frames** | > 2,300 Bytes | **0 Bytes** | **-100%** |

![Runtime Async Eliminates Allocations (0 Bytes Chart)](/dotnetconf2026/archive/16-runtime-vnext-memory-safety-async/screenshots/07_zero_byte_allocation_chart.webp)

### Execution Latency Across Stack Depth
In benchmarks modeling backup file walkers (where most files check timestamps synchronously without blocking threads), Runtime Async overhead stays nearly flat while compiler async latency compounds linearly:

| Call Depth | State Machines Latency | Runtime Async Latency | Speedup |
|---|---|---|---|
| **3 Frames** | 1.487 µs | 1.399 µs | **1.06x faster** |
| **5 Frames** | 1.547 µs | 1.431 µs | **1.08x faster** |
| **7 Frames** | 1.621 µs | 1.437 µs | **1.13x faster** |

![The performance advantage grows with async depth](/dotnetconf2026/archive/16-runtime-vnext-memory-safety-async/screenshots/06_sync_performance_frame_depth.webp)

### Clean Call Stacks for Diagnostics
Because CoreCLR suspends and resumes methods natively on the execution thread without synthesising state machines, `Environment.StackTrace` outputs clean, human-readable method lists without state machine boilerplate:

![Async Call Stack Comparison](/dotnetconf2026/archive/16-runtime-vnext-memory-safety-async/screenshots/05_stack_trace_comparison.webp)

```text
// Legacy Compiler Async Stack Trace:
at OrdersController.<Get>d__0.MoveNext()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine)
at OrdersController.Get(Int32 id)

// Runtime Async Stack Trace (Identical to synchronous code):
at OrderService.LoadAsync(Int32 id)
at OrderService.GetOrderAsync(Int32 id)
at OrdersController.Get(Int32 id)
```

### Exception Handling & Outage Resilience
During service outages or network failures ("exception storms"), traditional async incurs severe latency penalties because exceptions must be caught, unwrapped, and rethrown across every state machine frame.
* **Non-Suspending Async Exceptions:** **2.5x faster** at 8 frames.
* **Suspending Async Exceptions:** **3.4x faster** at 8 frames.
* **32 Frames Deep:** Runtime Async exception dispatch is so efficient that it actually **runs faster than synchronous exception handling**.

![Runtime Async Exception Handling Performance](/dotnetconf2026/archive/16-runtime-vnext-memory-safety-async/screenshots/08_async_exception_handling_perf.webp)

---

## 3. Memory Safety V2: Elevating C# to Rust and Swift Parity

### Industry Motivation & Government Directives
Research by Microsoft Security Response Center (MSRC) and Google confirms that **70% of all software security vulnerabilities are caused by memory safety violations** (out-of-bounds writes, uninitialized reads, use-after-free).

While C# has been memory safe since 1.0 via garbage collection, definite assignment, and array bounds checking, developers and low-level libraries rely on "escape hatches" (`unsafe` pointers, native interop, unmanaged buffers). Previously, C# provided no compiler mechanism to enforce safety obligations across caller/callee boundaries.

![Making C# code safer: Memory Safety V2 MSBuild options](/dotnetconf2026/archive/16-runtime-vnext-memory-safety-async/screenshots/09_memory_safety_v2_optin.webp)

### Opting In to Super-Safe Mode
```xml
<PropertyGroup>
    <LangVersion>preview</LangVersion>
    <MemorySafetyRulesVersion>2</MemorySafetyRulesVersion>
    <AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
```

When `<AllowUnsafeBlocks>false</AllowUnsafeBlocks>` is configured alongside Memory Safety Rules v2, no unvalidated unsafe code can be compiled—providing absolute safety guarantees against accidental memory corruption by developers or autonomous AI coding agents.

### The Contract and Blame System
Memory Safety V2 introduces a formal contract and blame model:
1. **Unsafe Obligations:** Any API performing memory-unsafe operations must explicitly declare the preconditions required of the caller.
2. **Obligation Documentation:** Authors use the XML `<safety>` tag to document required invariants.
3. **Unsafe Fields:** Struct and class fields holding raw pointers or unmanaged memory handles participate directly in unsafe contracts.
4. **Explicit Boundary Verification:** Callers must prove invariants before calling unsafe members or encapsulate them within safe facades.

### Safe Facades & Unsafe Expressions
To make memory safety ergonomic without the syntactical tax of curly-brace blocks, C# introduces **Unsafe Expressions** (`unsafe(...)`):

![Unsafe Inside BitConverter.ToUInt64](/dotnetconf2026/archive/16-runtime-vnext-memory-safety-async/screenshots/10_unsafe_expressions_syntax.webp)

```csharp
// Example from System.BitConverter: Safe facade wrapping unsafe intrinsic
public static ulong ToUInt64(ReadOnlySpan<byte> value)
{
    // 1. Runtime guard guarantees boundary invariant
    if (value.Length < sizeof(ulong))
        ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
    
    // 2. Unsafe expression: caller obligations satisfied, blame accepted locally
    return unsafe(Unsafe.ReadUnaligned<ulong>(
        ref MemoryMarshal.GetReference(value)));
}
```

### Tri-Language Parity (C#, Rust, Swift)
Rich and Andy highlighted that C# now directly aligns with the memory safety models of **Rust** and **Swift** (2025 release):
* All three languages enforce safe abstractions over unsafe primitives.
* All three enforce explicit caller obligations via the `unsafe` keyword.
* All three prevent compiler compilation if unsafe operations are attempted without acknowledging the contract.

---

## Key Takeaways for Developers

1. **Test `<Features>runtime-async=on</Features>` Today:** Gain immediate memory allocation reductions (0-byte synchronous completions) and cleaner diagnostics in .NET 11 before it becomes the default in .NET 12.
2. **Prepare for Memory Safety V2:** Review low-level and P/Invoke codebases, encapsulate native pointers within safe `ReadOnlySpan<T>` facades, and utilize unsafe expressions (`unsafe(...)`).
3. **Zero Allocation Mindset:** High-throughput backend services (Kestrel, Aspire, microservices) can safely use `async`/`await` throughout deep layers without fear of state-machine memory tax.
