2014-07-13 122 views
2

這是一個非常基本的問題。我正在調試一些內存泄漏,並完全困惑。假設我有以下幾點:.NET垃圾回收器

public class ObjectData : IDataObject 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

public class ObjectRepository<T> where T : IDataObject 
{ 
    private Dictionary<int, T> Objects; 

    public ObjectRepository() 
    { 
     Objects = new Dictionary<int, T>(); 
     // load Data 
    } 

    public T GetDataObject(int id); 
    { 
     return Objects[id]; 
    } 

    public Reset() 
    { 
     Objects = new Dictionary<int, T>();; 
    } 
} 

現在假設我有以下程序流程:

public Main() 
{ 
    var DataRepository = new ObjectRepository<ObjectData>(); 

    // Constructor called and Data loaded 

    var myObject = DataRepository.GetDataObject(1); 

    DataRepository.Reset(); 

    // Call manually the garbage collector or leave it 

    // Program flow continue after this 
} 

的問題是,將垃圾收集擺脫最初由構造函數創建的集合?或者它不會因爲程序流程中仍然引用了其中一個元素(myObject)?

回答

1

它將被收集(最終),因爲沒有更多的引用它。在字典中獲取對某些東西的引用並不會給你任何對字典本身的引用!除非該對象以某種方式在內部引用字典,否則。

+0

感謝您的提示!關於內部參考:) –

1

在您致電Reset後,沒有強烈提及您的初始dictionary。因此,它將被選爲垃圾收集。

或者它不會因爲其中一個元素仍然在程序流(myObject)中被引用?

字典引用哪些對象並不重要,重要的是誰指的是字典。在這種情況下,沒有人。在內容仍然存在的情況下收集字典是完全可能的。

1

要回答這樣的問題,請問自己:誰在引用有問題的對象(在這種情況下是被覆蓋的字典)?

DataRepository不是。您重寫了指向舊字典的對象引用。

myObject不是因爲ObjectData沒有任何字段類型的字典。它不能引用字典。

沒有人留下來引用舊的字典。