Skip to main content
 首页 » 编程设计

c#之DataRow 未被 GC 收集

2024年02月23日17qq78292959

我的应用程序出现泄漏一些内存的问题。长时间运行时,这将成为一个真正的问题。 我基本上有以下类(class):

public class FeaturesDataSource{ 
     // Table used only for schema hosting 
     DataTable selectedFeaturesDataTable; 
     IDictionary<uint, MyFeatureType > _selectedFeaturesCache =  
          new Dictionary<uint, MyFeatureType>(); 
     // Create table according to a defined schema... 
 
     // Adds or replaces an existing feature 
     public void AddFeature(int featureID, MyFeatureType featureValue) { 
           DataRow row = selectedFeaturesDataTable.NewRow(); 
           row["ID"] = featureID; 
           row["Content"] = featureValue; 
           if (_selectedFeaturesCache.ContainsKey(featureID) { 
               _selectedFeaturesCache.Remove(featureID); 
           } 
           _selectedFeaturesCache.Add(featureID, row); 
     } 
} 

从这个方法可以看出,调用AddFeature根据表的架构创建一个新数据行并替换任何具有相同 ID 的现有数据行。 我的应用程序创建类型为 MyFeatureType 的对象以 1 个对象/秒的速率调用 AddFeature每次都使用相同的 ID:

// This data source gets updated in the following way 
public void MethodCalledEverySecond(MyFeatureType featureValue){ 
     // This data source contains only one object of type MyFeatureValue,  
     // replace the existing one by specifying a constant ID 
     myFeatureDataSource.AddFeature(1, featureValue);   
} 

这应该始终用新数据行替换现有数据行。 在运行时,VS 显示 _selectedFeaturesCache字典计数总是等于 1,这是预期的,但是 !dumpHeap -stat显示越来越多的 MyFeatureType 类型的对象在内存中它应该总是等于 1。 我在这里做错了什么吗? selectedFeaturesDataTable.NewRow()保留对被替换的旧数据行的引用以阻止 GC 收集它们?

请您参考如下方法:

根据 NewRow 方法的文档 here:

When you use NewRow to create new rows, the rows must be added to or deleted from the data table before you call Clear

这似乎暗示存在对创建行的数据表的引用。

我认为您需要先调用 Delete 然后再调用 AcceptChanges 以将其从表中分离。