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!
That's an improper use of Dispose()
.
Dispose()
is intended for use in two cases:
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With