C# Dispose object after using in list?

13,299

Solution 1

That's an improper use of Dispose().

Dispose() is intended for use in two cases:

  1. When you are disposing unmanaged resources.
  2. When you are disposing an object of a type that itself implements IDisposable.

You should rename your Dispose() method to be something like Clear() to better describe what is happening.

Alternatively (and I think probably better in your case) you could simply set the listQ reference to null once you have iterated over it. Since you are destroying the data it holds as you iterate over it, it is clear that you don't need the data afterwards.

If you set the listQ reference to null, all its memory, including that of all the objects that it holds references to, will (eventually) be garbage-collected, assuming that nothing else holds references to those objects.

Note that you'd have to make sure that all references to listQ are set to null. (References to it on the stack will automatically disappear when the method they are declared in return, so you don't need to worry about those.)

Solution 2

If possible, use the Queue class instead of List. This way, when you Dequeue, you automatically remove the object from the collection:

while(queueCollection.Count > 0) {
    MyClass obj = queueCollection.Dequeue();
    obj.Execute();
}

Solution 3

I guess you are really worried about the objects eating up your memory.You dont have to unless you are using unmanaged resources like accessing a network or remote db resource.Since this is not your case,the runtime is intelligent enought to free up the resources when it deems necessary.

Garbage collection in .net runtime manages the Managed resources for you and you should not be worried too much about freeing up your managed handles.

When your List reference goes out of scope or when the GC knows that this list is not used ,the object will be cleared from memory.

Share:
13,299

Related videos on Youtube

Hùng Lê Xuân
Author by

Hùng Lê Xuân

I'm .NET developer, besides i have a knowledge about php, javascript, java. I like to become Android developer but i haven't found an environment to learn.

Updated on September 14, 2022

Comments

  • Hùng Lê Xuân
    Hùng Lê Xuân over 1 year

    I have a class and this class has "value" variable contain a big data reading from file :

     public class MyClass : IDisposable
    {
        public string name {get; set;}
        public string value {get; set;} //I'm load huge data for this variable
    
        public MyClass(string name, string value)
        {
            this.name = name;
            this.value = value;
        }
    
        public void Execute()
        {
            Console.WriteLine(this.name + ":" + this.value);
        }
    
        public void Dispose()
        {
            Dispose(true);            
            GC.SuppressFinalize(this); 
        }
    
        protected virtual void Dispose(bool disposing)
        {                     
            if (disposing)
            {
                this.name = null;
                this.value = null;
            }                      
        }
    }
    

    And i'm using this class in list that it's global variable

    List<MyClass> listQ = new List<MyClass>() { new MyClass("1", "BIGDATA1"),
                new MyClass("2", "BIGDATA2"),
                new MyClass("3", "BIGDATA3"),
                new MyClass("4", "BIGDATA4"),
                new MyClass("5", "BIGDATA5"),
                new MyClass("6", "BIGDATA6"),
            };
    
        private void FUC_Load(object sender, EventArgs e)
        {                        
            foreach (MyClass m in listQ)
            {
                m.Execute();
                m.Dispose();
            }                       
        } 
    

    So i wanna ask that if i do like that, will have any problem? My object will be disposed or not? Any the best way? Thank!

    • dotNET
      dotNET almost 11 years
      Also, if you're really only keeping Name and Value members, both of which are strings, you may better inherit from NameValueCollection instead of reinventing the wheel.