Disposing a stream closes it (and probably doesn't do much else.) Closing a stream flushes it, and releases any resources related to the stream, like a file handle. Flushing a stream takes any buffered data which hasn't been written yet, and writes it out right away; some streams use buffering internally to avoid making a ton of small updates to relatively expensive resources like a disk file or a network pipe.
You need to call either Close
or Dispose
on most streams, or your code is incorrect, because the underlying resource won't be freed for someone else to use until the garbage collector comes (who knows how long that'll take.) Dispose
is preferred as a matter of course; it's expected that you'll dispose all disposable things in C#. You probably don't have to call Flush
explicitly in most scenarios.
In C#, it's idiomatic to call Dispose
by way of a using
block, which is syntactic sugar for a try-finally block that disposes in the finally, e.g.:
using (FileStream stream = new FileStream(path))
{
// ...
}
is functionally identical to
FileStream stream;
try
{
stream = new FileStream(path);
// ...
}
finally
{
if (stream != null)
stream.Dispose();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…