为什么堆内存一直在增加? C#

问题描述 投票:0回答:1

主要是我从数据库中获取一些记录的方式:

public static class AnimalService
{

    public static AnimalsDto GetAnimals(int limbCount)
    {
        var animals = GetAnimalsByLimbCount(limbcount)
    
        return new AnimalsDto(){
            Animals = animals,
            Count = animals.Count(),

    }

    private static IEnumerable<Animal> GetAnimalsByLimbCount(int limbCount)
    {
        List<Animal> animals = new List<Animal>();

        using (SqlConnection connection = new SqlConnection(...)) // some connection string
        {
            connection.Open();

            SqlCommand command = connection.CreateCommand();

            command.CommandText = $"SELECT * FROM Animals WHERE limb_count = {limbCount}";

            var reader = command.ExecuteReader()
                
            while (reader.Read())
            {
                Animal animal = new Animal()
                {
                    Name = reader[0].ToString(),
                };

                animals.Add(animal);
            }                                
            connection.Close();
        }
        return animals;
    }

}

public class AnimalsDto
{
    public IEnumerable<Animals> Animals { get; set; }
    public int Count { get; set; }
}

然后我每隔一段时间调用服务:

while(true){
    var animals = AnimalService.GetAnimals(4);
    //some delay happening
}

堆大小在应用程序运行时不断增加。


\>>> Profiler 图片

拍了一张快照后,我注意到了

List<Animal> animals

没有被 GC 从堆内存中清除,而是每次被添加到堆中

private static IEnumerable<Animal> GetAnimalsByLimbCount(int limbCount)
{
...
}

正在呼叫。

如何让GC清除堆内存中剩余的对象?

c# memory-leaks garbage-collection heap-memory
1个回答
0
投票

如何让GC清除堆内存中剩余的对象?

通过确保无法从任何 GC 根访问对象。这些包括当前线程堆栈和静态变量。您可以通过检查分析器中的堆来了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.