打赏

【C#】垃圾回收GC

 官方文档链接

            //强制对所有代进行即时垃圾回收。
            GC.Collect();
            //强制对 0 代到指定代进行即时垃圾回收。
            GC.Collect(1);
            //强制对0代到指定代垃圾回收
            //Forced:强制立即执行垃圾回收
            //Optimized:使垃圾回收器可以确定当前时间是否是回收对象的最佳时间
            GC.Collect(1, GCCollectionMode.Forced);
            //强制对0代到指定代垃圾回收  Optimized:使垃圾回收器可以确定当前时间是否是回收对象的最佳时间
            //另有数值指定回收是否应该为阻碍性(true:执行阻碍性垃圾回收,false:在可能的情况下执行后台垃圾回收)
            GC.Collect(1, GCCollectionMode.Optimized, true);
            //强制对0代到指定代垃圾回收  Optimized:使垃圾回收器可以确定当前时间是否是回收对象的最佳时间
            //另有数值指定回收是否应该为阻碍性
            //另有数值指定回收是否应该为压缩性 (true:压缩小对象堆,false:仅进行清理)
            GC.Collect(1, GCCollectionMode.Optimized, true, true);
               
View Code

 

 

最佳实践

1.值类型

值类型用作本地栈变量时,其分配开销是最小的。

值类型用作本地栈变量时,不需要回收开销,在方法结束栈解退时,他们就自动销毁了。

2.对象图

对象图的体积直接影响倒垃圾回收器工作量的大小。

3.对象池

对象词是一个使用手动方式,而非依赖于运行环境提供的相应功能,管理托管内存和资源的机制。

4.分页及非托管内存分配

一个自定义的CLR宿主可以将部分CLR的内存分配请求涉及的页面锁定在物理内存中。

5.静态代码分析规则

有关使用不使用VS进行托管代码分析的更多信息,参见msdn在线文档。

 

.NET Core中的垃圾回收

https://stackoverflow.com/questions/51460763/azure-app-services-high-memory-consumption-net-core

 

because the settings have moved to the ASPNETCore.csproj file for Visual Studio 2017, you need to change the “ServerGarbageCollecton” XML node from “true” to “false“:

<PropertyGroup> 
    <ServerGarbageCollection>false</ServerGarbageCollection>
</PropertyGroup>

 

This is because according to Mark Vincze:

the CPU count greatly affects the amount of memory .NET will use with Server GC

 

And since all of the DiscountASP.NET’s servers run on multiple processors, changing this value should reduce the amount of memory that your .NET Core application will use.  Many thanks to Mark Vincze and his tests to help the .NET Community out.

https://blog.discountasp.net/reducing-net-core-memory-usage/

 

posted @ 2019-03-07 14:36  cksun  阅读(395)  评论(0)    收藏  举报