Stream.Write Stream Security

The MSDN documentation states that instance methods that include Stream.Write of the Stream class are not guaranteed to be thread safe, but what does that mean? What happens if one thread tries to call Stream.Write on a Stream object before another thread returns from the same method on the same object? Will an exception be thrown, or will the object queue the data to be sent in accordance with the order of the flows? Some say it’s normal to call without a blocking mechanism. Can anyone clarify this?

+4
source share
2 answers

This means that you should never call instance methods, such as reading and writing to the same stream instance from different threads at the same time. You will get unexpected behavior. In some cases, an exception may be thrown, otherwise your data may be damaged, and in another it may even work (if you're lucky).

You always need to synchronize access to such shared resources using appropriate locking mechanisms if you intend to use them from multiple threads.

+3
source

Write is an abstract method, which means that the behavior of this method is defined in Stream subclasses. Some Stream subclasses may provide thread-safe Write methods, while others may not. Thus, you cannot tell how the Stream will behave if you call it with the Write method from different threads at the same time, if you do not know which specific subclass of Thread you are dealing with.

Therefore, you should use locking when working with Stream objects, since MSDN says that Stream methods are not guaranteed by thread safety, so there may be threads that can be interrupted when called at the same time.

But if you explicitly use certain subclasses of Stream, and know that they are thread-safe, then there is no need to block.

0
source

All Articles