Pregunta

I have a scenario with related but different questions. So it may look like a duplicated post but it’s not

I’m working on a class that uses a TcpClient eventually created on the UI thread to read and write data. When the TcpClient is created the design is to connect to a server and create a BinaryReader and BinaryWriter immediately.

The BinaryReader is used on a dedicated thread that does a blocking read. When data arrives I generate an event and pass the data for processing. Rinse and repeat.

The BinaryWriter is used when data arrives on another thread. Right now it happens to be the UI thread, but it doesn’t have to be. One thing that is known is that it won’t be the same thread that the blocking reader is running.

Because I create the binary handlers upfront I found that making sure they are disposed of properly is tricky. It seems that it would be much easier to use a using statement to encapsulate their life where they are being used.

However I know that creating an object that you could reuse is wasteful and adds a load to system. Especially with the BinaryWriter that would leave its scope after a single use.

What is the best practice for these classes and for IDisposable objects in general?

¿Fue útil?

Solución

No, this is not necessary. The only reason that BinaryReader/Writer implement IDisposable is because they assume ownership of the Stream that you pass to its constructor. Standard behavior for classes that handle streams in the .NET Framework.

But the Stream you pass is a NetworkStream that's owned by your TcpClient object. Which itself already implements IDisposable, it uses its Dispose method to dispose both the NetworkStream and the Socket.

So this is already taken care of, when you close the client then the stream is already disposed. No need to dispose it again through the reader and/or writer.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top