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?

+2


source to share


4 answers


No, it is not safe to blindly call the Close method from a separate thread. The Stream class is not listed as thread safe and calls Close from another stream while the original stream is using it will result in undefined behavior.



+2


source


Yes, if the inputStream is reading from a socket, then you can use another stream that will close the socket connection. You should be aware that a blocking Read call will throw an exception.



+1


source


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. If IsDone

    true, ignore the data and close the stream.

This should avoid any issues that Jared refers to.

+1


source


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.

0


source







All Articles