Can anyone explain a WPF memory leak using FileStream?

I open a series of large files in a loop and I get a memory leak that I don't understand. The following code does not create a memory leak:

DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(List<GeographicalEntity>), GetKnownTypes()); List<GeographicalEntity> temporaryEntities; using (FileStream fileStream = new FileStream(dataFilePath, FileMode.Open)) { temporaryEntities = dataContractSerializer.ReadObject(fileStream) as List<GeographicalEntity>; } geographicalEntities.AddRange(temporaryEntities); temporaryEntities.Clear(); temporaryEntities = null; dataContractSerializer = null; 

In contrast, the memory usage of the following code continues to increase:

  DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(List<GeographicalEntity>), GetKnownTypes()); List<GeographicalEntity> temporaryEntities; using (FileStream fileStream = new FileStream(dataFilePath, FileMode.Open)) { temporaryEntities = dataContractSerializer.ReadObject(fileStream) as List<GeographicalEntity>; } geographicalEntities.AddRange(temporaryEntities); //temporaryEntities.Clear(); //temporaryEntities = null; dataContractSerializer = null; 

I do not understand why the “temporary events” need to be cleared and canceled. There are no other references to this variable. Can anyone explain this behavior?

+4
source share
2 answers

geometientEntities.AddRange () seems to be collecting GeographicalEntity lists.

Why not use memory?

The reason the first one fails is because you add them and then clear them again, so there is a set of empty lists in the list of geographic features.

EDIT: Actually just realized that geographic features are also a <> list, so my last sentence doesn't apply.

I would suggest that the cited code is not representative of the real thing. The entire read file is meaningless in the cited code, so I would suggest that something is lost in simplification.

0
source

Are you sure that the difference is not in using temporary Entities.Clear () or not? Because he is also commented.

When a collection contains an object, this object will not be marked for garbage collection (this is also a link).

0
source

Source: https://habr.com/ru/post/1381163/


All Articles