XmlWriter: is calling Close() required if using a using block?
Is it sufficient to create an Xml开发者_开发百科Writer with a using block (with no call to Close()) or is it better to use a try/finally block and call Close() in finally?
The using block is a shortcut for a try/finally block with a call to Dispose() on any object that implements IDisposable.
In the case of streams and stream writers, Dispose() generally calls Close() manually. Using reflector, here's the Dispose method of XmlWriter:
protected virtual void Dispose(bool disposing)
{
if (this.WriteState != WriteState.Closed)
{
try
{
this.Close();
}
catch
{
}
}
}
So the short answer is yes, the using
block will handle closing the XmlWriter for you.
No, calling it separately is not required. That's exactly what the using block is for.
When execution exits the using block, the XmlWriter is disposed, and on the inside, XmlWriter.Dispose
calls XmlWriter.Close
.
But... Reflector on the XmltTextWriter.Close() show :
if(this.closeOutput) { this.stream.Close(); } this.Stream = null;
the closeOutput flag is set to settings.CloseOutput, which can be false.
Are you sure the handler is free when using "using" expression on the XmlTextWriter ?
精彩评论