简体   繁体   English

Rx.Net 内存泄漏

[英]Rx.Net memory leak

An interesting memory leak.一个有趣的内存泄漏。 Does anyone know why?有谁知道为什么?

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

Where:在哪里:

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();        
}

There's actually no memory leak.实际上没有内存泄漏。

GC.GetTotalAllocatedBytes is a count of the bytes allocated over the lifetime of the process. GC.GetTotalAllocatedBytes是在进程的生命周期内分配的字节数。 Every time there's a heap allocation, this counter goes up.每次有堆分配时,这个计数器都会上升。

What you want to use instead is GC.GetTotalMemory .你想要使用的是GC.GetTotalMemory

If you see the deltas between your test values, you'll see that they're approximately the same.如果您看到测试值之间的差异,您会发现它们大致相同。

三角洲

You'll see some minor variations in your tests related to memory pressure.您会在与内存压力相关的测试中看到一些细微的变化。

GC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM