0

I have one single configuration XML file which can be deserialised into different instances, each of which takes only a portion of this XML.

class A
{
    public string A { get; set; }
}

class B
{
    public string B { get; set; }
}

public static T Xml2Cls<T>(string filename)
{
    XDocument doc = XDocument.Load(filename);
    var root = new XMLRootAttribte(doc.Root.Name.LocalName);
    var serializer = new XMLSerializer(typeof(T), root);
    using (var reader = doc.Root.CreateReader())
    {
        return (T)serializer .Deserialize(reader);
    }
}

// if I keep calling the following for say 1000 times
// all these instances don't seem to get garbage collected
var a = Xml2Cls<A>("a.xml");
var b = Xml2Cls<B>("a.xml");

<root>
    <a>...</a>
    <b>...</b>
</root>

Any ideas why those instantiated objects are not garbage collocted? I tried moving the return out of the using block but it doesn't make a difference.

16
  • 3
    So what is the actual question? It should be clearly summarized in the title and expanded/clarified outside of the code block. Commented Jul 9, 2019 at 23:23
  • 1
    Why do you believe var a = … somehow should be instantly garbage collected? Or you are asking about some other objects ? (Very unclear at this point what exactly is the problem) Commented Jul 10, 2019 at 0:29
  • 2
    "So as soon as that function returns, they should be destroyed."???? Can you show minimal reproducible example that explains why you expect that behavior of GC? Where "collected 1 minute or so later" comes from? (I don't think there any configuration you can set to make GC to behave that way - so clearly you have code that force GC - make sure to include that in sample) - again showing good self-contained example would be really helpful. Commented Jul 10, 2019 at 0:48
  • 1
    @Antediluvian bing.com/search?q=c%23+xmlserializer+outofmemory - should be duplicate of stackoverflow.com/questions/2805738/… (but I already used up my vote) Commented Jul 10, 2019 at 1:53
  • 1
    You don't provide real code. If you have 1000 variables a, b,... and each string is a 1MB file, then it it possible to get out-of-memory because you have 1GB of memory just for that (a 32 bit application would have 2GB available for user in theory. It could be a bit less in practice) Commented Jul 10, 2019 at 1:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.