스트림 객체에 대해 Close () 또는 Dispose ()를 호출해야합니까?
같은 클래스 Stream, StreamReader, StreamWriter등을 구현하는 IDisposable인터페이스를 제공합니다. 즉, Dispose()이러한 클래스의 객체에서 메소드를 호출 할 수 있습니다. 또한 public라는 메소드를 정의했습니다 Close(). 이제 객체로 작업을 마치면 무엇을 호출해야하는지에 대해 혼동됩니다. 둘 다 호출하면 어떻게됩니까?
내 현재 코드는 다음과 같습니다
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
using (StreamWriter writer = new StreamWriter(filename))
{
int chunkSize = 1024;
while (!reader.EndOfStream)
{
char[] buffer = new char[chunkSize];
int count = reader.Read(buffer, 0, chunkSize);
if (count != 0)
{
writer.Write(buffer, 0, count);
}
}
writer.Close();
}
reader.Close();
}
}
보시다시피, 나는 각 객체에 대해 using()자동으로 Dispose()메소드를 호출하는 구문을 작성했습니다 . 그러나 나는 또한 Close()메소드 를 호출 합니다. 맞아?
스트림 객체를 사용할 때 모범 사례를 제안하십시오. :-)
MSDN 예제는 using()구문을 사용하지 않고 Close()메소드를 호출 합니다.
좋은가요?
Reflector.NET으로 빠르게 점프하면 Close()방법 StreamWriter이 다음과 같습니다.
public override void Close()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
그리고 StreamReader:
public override void Close()
{
this.Dispose(true);
}
Dispose(bool disposing)에서 무시 StreamReader된다
protected override void Dispose(bool disposing)
{
try
{
if ((this.Closable && disposing) && (this.stream != null))
{
this.stream.Close();
}
}
finally
{
if (this.Closable && (this.stream != null))
{
this.stream = null;
/* deleted for brevity */
base.Dispose(disposing);
}
}
}
StreamWriter방법은 비슷합니다.
그래서, 코드를 읽는 것은 그것이 분명 당신이 호출 할 수있는 Close()& Dispose()좋아하고 어떤 순서로 당신만큼 자주 스트림에. 어떤 식 으로든 동작을 변경하지 않습니다.
그래서 그것을 사용하는 것이 더 읽을 수 있는지 여부에 내려 오는 Dispose(), Close()및 / 또는 using ( ... ) { ... }.
개인적으로 선호하는 것은 using ( ... ) { ... }가위로 달리지 않는 데 도움이되므로 가능한 한 항상 사용하는 것이 좋습니다.
But, while this helps correctness, it does reduce readability. In C# we already have plethora of closing curly braces so how do we know which one actually performs the close on the stream?
So I think it is best to do this:
using (var stream = ...)
{
/* code */
stream.Close();
}
It doesn't affect the behaviour of the code, but it does aid readability.
No, you shouldn't call those methods manually. At the end of the using block the Dispose method is automatically called which will take care to free unmanaged resources (at least for standard .NET BCL classes such as streams, readers/writers, ...). So you could also write your code like this:
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
using (StreamWriter writer = new StreamWriter(filename))
{
int chunkSize = 1024;
while (!reader.EndOfStream)
{
char[] buffer = new char[chunkSize];
int count = reader.Read(buffer, 0, chunkSize);
if (count != 0)
{
writer.Write(buffer, 0, count);
}
}
}
The Close method calls Dispose.
The documentation says that these two methods are equivalent:
StreamReader.Close: This implementation of Close calls the Dispose method passing a true value.
StreamWriter.Close: This implementation of Close calls the Dispose method passing a true value.
Stream.Close: This method calls Dispose, specifying true to release all resources.
So, both of these are equally valid:
/* Option 1 */
using (StreamWriter writer = new StreamWriter(filename)) {
// do something
}
/* Option 2 */
StreamWriter writer = new StreamWriter(filename)
try {
// do something
}
finally {
writer.Close();
}
Personally, I would stick with the first option, since it contains less "noise".
On many classes which support both Close and Dispose methods, the two calls would be equivalent. On some classes, however, it is possible to re-open an object which has been Close'd. Some such classes may keep some resources alive after a Close, in order to permit reopening; others may not keep any resources alive on Close, but might set a flag on Dispose to explicitly forbid re-opening.
The contract for IDisposable.Dispose explicitly requires that calling it on an object which will never be used again will be at worst harmless, so I would recommend calling either IDisposable.Dispose or a method called Dispose on every IDisposable object, whether or not one also calls Close.
참고URL : https://stackoverflow.com/questions/7524903/should-i-call-close-or-dispose-for-stream-objects
'Programming' 카테고리의 다른 글
| flexbox 항목이 열 모드로 줄 바꿈 될 때 컨테이너의 너비가 커지지 않습니다 (0) | 2020.06.22 |
|---|---|
| 명시 적으로 파일을 닫는 것이 중요합니까? (0) | 2020.06.22 |
| 왜 서로 다른 두 개념이“힙”이라고 불리는가? (0) | 2020.06.22 |
| JBoss vs Tomcat 다시 (0) | 2020.06.22 |
| C ++를 컴파일하기 위해 Windows를 Linux만큼 빠르게 실행하려면 어떻게해야합니까? (0) | 2020.06.22 |