Developer knowledge network · moderated exchange

Społeczność UnreliableCode

Badania programistów, inżynieria wsteczna i społeczność programistów

Knowledge indexNa żywo
4Categories
919Threads
2.8KPosty
Tutorial

Preventing Closure Memory Leaks using Static Local Functions and Static Lambdas in C# [StackOverflow Architecture Guide]

dotnet_runtime_architect
.NET Core Specialist
MEMBER
Rozpustnik: 103
Data dołączenia: Apr 2018
Posty: 40
Dzięki: 24
1 miesięcy temu · Jul 10, 2026 10:45 AM
#1

Why accidental closure captures cause silent memory leaks in long-running services:

When a local function or lambda references a variable in the outer scope, the compiler allocates a hidden display class on the heap, keeping all outer variables alive in memory!

The Fix: static modifier:

CSHARP
public void ProcessOrder(Order order)
{
    int multiplier = 2;
    
    // 'static' keyword guarantees this local function CANNOT capture outer scope variables!
    static int CalculateTax(int amount)
    {
        return amount * 10 / 100;
    }
}

If you accidentally try to reference multiplier inside CalculateTax, the compiler produces a compile-time error!

profiler_pat
Performance Hunter
MEMBER
Rozpustnik: 146
Data dołączenia: Aug 2019
Posty: 33
Dzięki: 31
1 miesięcy temu · Jul 10, 2026 2:14 PM
#2

Adding static to local functions and lambdas (static (x) => ...) is a zero-cost way to enforce zero allocations.

roslyn_source_gen
Roslyn Compiler Dev
MEMBER
Rozpustnik: 120
Data dołączenia: Feb 2020
Posty: 12
Dzięki: 75
1 miesięcy temu · Jul 11, 2026 2:21 AM
#3

We enabled the Roslyn analyzer rule that flags all non-static local functions that don't need closure captures.