主要是我从数据库中获取一些记录的方式:
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
}
堆大小在应用程序运行时不断增加。
拍了一张快照后,我注意到了
List<Animal> animals
没有被 GC 从堆内存中清除,而是每次被添加到堆中
private static IEnumerable<Animal> GetAnimalsByLimbCount(int limbCount)
{
...
}
正在呼叫。
如何让GC清除堆内存中剩余的对象?