Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Dispose object after using in list?

Tags:

c#

dispose

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!

like image 634
Hùng Lê Xuân Avatar asked Dec 15 '22 11:12

Hùng Lê Xuân


1 Answers

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.)

like image 69
Matthew Watson Avatar answered Dec 21 '22 23:12

Matthew Watson