Alp
Alp

Reputation: 583

Thread Safety of Stream.Write method

MSDN documentation says that instance methods, which includes Stream.Write, of Stream class are not guaranteed to be thread-safe but what does it mean? What will happen if one thread tries to call Stream.Write on a Stream object before other thread haven't returned from the same method on same object? Will an exception be thrown, or the object will queue the data to send according to the order of threads? Some say it is ok to call without a locking mechanism. Can someone clarify this?

Upvotes: 4

Views: 447

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

It means that you should never call instance methods such as Read and Write on the same instance of Stream from different threads at the same time. You will get unexpected behavior. In some cases an exception might be thrown, in other your data might be corrupted and in other it might even work (if you are lucky enough).

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

Upvotes: 3

ilya
ilya

Reputation: 1

Write is abstract method, which means that behavior of that method is defined in Stream's subclasses. Some of Stream's subclasses could provide thread-safe Write methods, while others wouldn't. So you can't say how Stream will behave if you call it's Write method from different threads concurrently, unless you know what specific Thread subclass you're dealing with.

So you should use locking when working with Stream objects, since MSDN says that Stream's methods are not guaranteed to be thread-safe, so there are probably Streams that could break when called concurrently.

But if you're explicitly using specific Stream's subclasses, and you know that it's thread-safe, then there is no need for locking.

Upvotes: 0

Related Questions