开发者

Garbage collection and property syntax

I have a class that needs information from an xml file. I have another class which is constructed to meet that need. Once the information required is in the first class I want the xml reader to be garbage collect开发者_JAVA百科ed.

Now the xml reader gets the information required and stores it in private fields. The first class queries these fields and retrieves the information. I know that if I query the fields using functions provided in the xml reader there will be no residual linkage, will this also be the case if I use properties in the xml reader?

public float Var
{
    get { return someVar; }
    set { someVar = value; }
}


Not quite clear your question. You could use the XmlReader in a using if you want to allow that instance to be garbage collected once you process your XML file. Assigning the properties to private variables as you have said sounds correct. GC can collect the XmlReader instance if there are no live references. You could try below example.

using statement, defines a scope, outside of which an object or objects will be disposed. It's a good practice to call the Dispose method for objects like XmlReader that have file handlers.

   var myProperties;

    using (XmlReader reader = XmlReader.Create("file1.xml"))
    {
        while (reader.Read())
        {
                // myProperties = reader.....;
            }
        }
    }

Above code is a good way to check whether there is any issue with garbage collection because it will throw an exception in any case if you try to refer XmlReaders properties out side of the using statement. If you have assigned the values to private variables that should be fine.


If you have a reference to the XmlReader (eg, in a field in your class), it cannot be garbage-collected while the owning instance is still alive.

Once you don't have any references to it, it will be garbage-collected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜