2019-5-21-dotnet-使用-GC.GetAllocatedBytesForCurrentThread-获取当前线程分配过的内存大小...

title author date CreateTime categories
dotnet 使用 GC.GetAllocatedBytesForCurrentThread 获取当前线程分配过的内存大小
lindexi
2019-05-21 11:33:18 +0800
2019-04-23 09:37:27 +0800
C# dotnet

在 dotnet framework 4.8 的时候支持调用 GC.GetAllocatedBytesForCurrentThread 获取当前线程分配过的内存大小

创建一个简单的控制台程序,在调用 GC.GetAllocatedBytesForCurrentThread 方法返回调用方法所在的线程的内存大小,代码请看GetAllocatedBytesForCurrentThread

调用 GC.GetAllocatedBytesForCurrentThread 返回的是当前线程从启动到调用这个方法分配的内存大小,这个内存大小不是指在 GC 回收之后占用的大小

如我使用下面代码 每次调用 Foo 的时候,从 GetAllocatedBytesForCurrentThread 返回的值会不断添加,而不会随着 foo 被回收减少

        private void Foo()
        {
            var foo = new byte[100];
        }

这个方法在调用某些事件申请的内存的时候非常有用,可以看到在调用某些方法申请的内存有多少

可以在进入某个事件或方法的时候先调用获取当前线程的内存分配过的大小,在调用方法完成之后再调用一次,对比两个值就知道在这个方法里面申请的内存需要多少

这个方法只有在 .NET Core 2.0 以上和 .NET Framework 4.8 以上才可以用到

GC.GetAllocatedBytesForCurrentThread Method (System)

原文地址:https://www.cnblogs.com/lindexi/p/12085681.html