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?