Can stream.Close be called from another stream?
Is it safe to close System.IO.Stream (or any of the wrappers or readers) from the second stream?
I have a read new System.IO.StreamReader(inputStream, Encoding.ASCII);
from the net and am considering closing it from another thread by closing it.
If this is not a good idea, then what other way to make the thread block on read access from returning?
source to share
A common approach to neat cleaning in this situation is:
- Set a value to indicate completion (for example
IsDone = true
) - Write some data to the socket so that the lock read will get some data.
- On a stream that is reading from a socket, check if the value is true
IsDone
before processing the data read. IfIsDone
true, ignore the data and close the stream.
This should avoid any issues that Jared refers to.
source to share
Yes, it is fine to close a thread on another thread, but be aware of the implications of this. If you do this and another thread is using that thread, you will get an exception. The right thing to do is to have either an event or a handle to wait for the reading thread to check if it should close. The pseudocode will look something like this: Subject 1. Delay the read operation and check if there is data to read.
if this data, read some data. if not, continue to check the wait handle. If it is installed, close it and exit otherwise, read another loop
Topic 2. If I have to shut down the network, signal that the wait command is still doing something.
Remember that if you are working with blocking, you will get an exception. I recommend to NEVER use a blocking socket, no reason. We actually do (almost) all of our async operations under the hood of System.Net, and the sync code paths just run the async code path and then block until they complete.
source to share