Stream.Write 方法的线程安全性
MSDN 文档说 Stream 类的实例方法(包括 Stream.Write)不能保证线程安全,但这是什么意思?如果一个线程尝试在其他线程尚未从同一对象上的同一方法返回之前对 Stream 对象调用 Stream.Write,会发生什么情况?会抛出异常,还是对象会按照线程的顺序将数据排队发送?有人说没有锁定机制就可以调用。有人可以澄清这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这意味着您永远不应该同时从不同线程对同一个 Stream 实例调用实例方法,例如 Read 和 Write。你会得到意想不到的行为。在某些情况下,可能会引发异常,在其他情况下,您的数据可能会损坏,而在其他情况下,它甚至可能有效(如果您足够幸运)。
如果您打算从多个线程使用此类共享资源,则需要始终使用适当的锁定机制来同步对此类共享资源的访问。
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.
Write 是抽象方法,这意味着该方法的行为是在 Stream 的子类中定义的。 Stream 的某些子类可以提供线程安全的 Write 方法,而其他子类则不能。因此,如果您同时从不同线程调用 Stream 的 Write 方法,您无法说明 Stream 将如何表现,除非您知道正在处理的特定 Thread 子类。
因此,在使用 Stream 对象时应该使用锁定,因为 MSDN 表示 Stream 的方法不能保证线程安全,因此可能存在并发调用时可能会中断的 Stream。
但是,如果您显式使用特定 Stream 的子类,并且您知道它是线程安全的,则不需要锁定。
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.