Rx.Net内存泄漏

Rx.Net memory leak

一个有趣的内存泄漏。有谁知道为什么?

foreach (int x in Enumerable.Range(0, 1_000_000)
    .Select(async i => i))
{
}

GC.Collect();
Console.WriteLine(GC.GetTotalAllocatedBytes()); // 1036542160

foreach (int x in Enumerable.Range(0, 1_000_000)
    .Select(async i => i))
{
}

GC.Collect();
Console.WriteLine(GC.GetTotalAllocatedBytes()); // 2072860704

foreach (int x in Enumerable.Range(0, 1_000_000)
    .Select(async i => i))
{
}

GC.Collect();
Console.WriteLine(GC.GetTotalAllocatedBytes()); // 3109160008

其中:

static class SelectAsync
{
    public static IEnumerable<TResult> Select<T, TResult>(
        this IEnumerable<T> source, Func<T, Task<TResult>> selector) =>
        source
            .ToObservable()
            .Select(value => Observable.FromAsync(() => selector(value)))
            .Concat()
            .ToEnumerable();        
}

实际上没有内存泄漏。

GC.GetTotalAllocatedBytes 是在进程的生命周期内分配的字节数。每次有堆分配时,这个计数器都会增加。

您要使用的是 GC.GetTotalMemory

如果您看到测试值之间的增量,您会发现它们大致相同。

您会在与内存压力相关的测试中看到一些细微差异。