简体   繁体   中英

Do I need to Dispose() of objects returned from TcpListener etc

TcpListener function AcceptTcpClient() (and its async friends) return a TcpClient , which implements IDisposable . TcpClient.GetStream() in turn returns a Stream, which is also disposable. Am I supposed to dispose of these objects?

For example, is this correct?

using (var client = listener.EndAcceptTcpClient(result))
using (var stream = client.GetStream())
using (var writer = new StreamWriter(stream, Encoding.ASCII))
using (var reader = new StreamReader(stream, Encoding.ASCII))
{
   //some code
}

Also, when my writer and reader are disposed, won't they both try to close the same stream object?

The short answer to your first question is yes. You should dispose of all objects that implement IDisposable. There are a few classes that do implement IDisposable that actually don't need to be disposed, but those are usually because it is a class that inherits from something else that Microsoft wanted to be generic, and some/many/most of their targetted implementations may/do need to be disposed so the interface is there even on implementations that they themselves don't need disposing.

The answer to your second question is no. Disposing of writer and reader should NOT close stream, as stream is it's own object with it's own lifetime. Just because writer/reader are gone does not mean you are done with stream, but alas... There are some classes in .NET that don't follow this, and they do close and/or try to dispose of objects that are passed to them when they really should not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM