Using () and positioning with multiple wrapped threads

I am right that you will need to use () for the outermost thread if you do, for example

MemoryStream mstr = new MemoryStream();

using(StreamWriter w = new StreamWriter(mstr)) {
    ....
}

How to dispose StreamWriter should also dispose / close the underlying stream, there is no need to do this:

using(MemoryStream mstr = new MemoryStream())
using(StreamWriter w = new StreamWriter(mstr)) {
    ....
}

(Note that these are just examples of how to remove wrapped threads without looking for alternatives, like just using StringWriter, etc.)

+3
source share
5 answers

My rule of thumb: if it implements IDisposable, delete it.

(, , ), StreamWriter.Dispose() , , , . , , Dispose(), -MemoryStreams ( , ).

, StreamWriter, , .

+7

using , . mstr, , :

using (MemoryStream mstr = new MemoryStream())
using (StreamWriter w = new StreamWriter(mstr) {
    ....
}

// cannot attempt to access mstr here

, mstr , .

MemoryStream mstr = new MemoryStream();
using (StreamWriter w = new StreamWriter(mstr) {
    ....
}

mstr.Write(...); // KABOOM! ObjectDisposedException occurs here!

, ( ), , .

+9

StreamWriter.Dispose Reflector, , , . "using", .

+4

. TextWriter Dispose

public void Dispose()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}

Dispose true. TextWriter.Dispose Method (Boolean)

, , TextWriter. Dispose .

, IDisposable , , Dipose true.

+3

using.

Always, with the exception of one well-known case of WCF proxy classes, where a design error can sometimes cause methods to Disposethrow an exception, losing the original exception.

0
source

Source: https://habr.com/ru/post/1714250/


All Articles