Search code examples
sql-serverxmlado.netsqlxml

using SQLXML in ADO.NET, who needs to dispose?


I cannot find an documented answer to this question. If I'm using a SqlXml object to pass a xml to a StoredProc, who is responsible of disposing the XmlTextReader I'm creating?

From what I found so far, the constructor already creates a copy of the xml I'm passing in, so I'm guessing I can dispose the reader right after creating the SqlXml object. But this is just a guess, because I don't know if the reader is used later on by ado.net.

tia Martin


Solution

  • Your assumption is correct. The constructor for SqlXml stores the contents of the XmlReader in a memory stream. It does not hold a reference to the XmlReader that's passed in.

    Decompiled SqlXml constructor:

    public SqlXml(XmlReader value)
    {
        if (value == null)
        {
            this.SetNull();
            return;
        }
        this.m_fNotNull = true;
        this.firstCreateReader = true;
        this.m_stream = this.CreateMemoryStreamFromXmlReader(value);
    }
    

    Thus you should dispose of the XmlTextReader or wait until it gets GC'ed. The former is usually preferred as it's more idiomatic.