For the second question: the Dispose()
method should be callable twice without problems (see IDisposable.Dispose()
:
If an object's Dispose method is called more than once, the object must ignore all calls after the first one.The object must not throw an exception if its Dispose method is called multiple times.Instance methods other than Dispose can throw an ObjectDisposedException when resources are already disposed.
A common case is when a Stream
object is passed to another Stream
object that takes "ownership":
using (var ms = new MemoryStream())
{
using (var sw = new StreamWriter(ms))
//using (var sw = new StreamWriter(zip, Encoding.UTF8, 4096, true))
{
}
// false: ms has already been disposed
bool canWrite = ms.CanWrite;
}
The StreamWriter
normally takes ownership on the underlying stream (in this case ms
), so that when the Dispose()
of the StreamWriter
is called so is the Dispose()
of the MemoryStream
... But note that even the MemoryStream
is in a using
block, so its Dispose()
will be called again.
There is no problem here, because the Dispose()
of the various Stream
classes are correctly implemented. If you want to avoid this double Dispose()
, nearly all the Stream
classes have an overload that tells them if they must take ownership on the underlying Stream
(see the commented row... The argument is called leaveOpen
, so by setting it to true
the StreamWriter
won't Dispose()
the underlying stream)