在不同的线程中使用从同一流源派生的 BinaryReader 和 BinaryWriter 是否安全? [英] Is it safe to use a BinaryReader and a BinaryWriter derived from the same stream source in separate threads?

查看:44
本文介绍了在不同的线程中使用从同一流源派生的 BinaryReader 和 BinaryWriter 是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含相关但不同问题的场景.所以它可能看起来像一个重复的帖子,但它不是

I have a scenario with related but different questions. So it may look like a duplicated post but it’s not

我正在开发一个类,该类使用最终在 UI 线程上创建的 TcpClient 来读取和写入数据.当创建 TcpClient 时,设计是连接到服务器并立即创建 BinaryReaderBinaryWriter.

I’m working on a class that uses a TcpClient eventually created on the UI thread to read and write data. When the TcpClient is created the design is to connect to a server and create a BinaryReader and BinaryWriter immediately.

BinaryReader 用于执行阻塞读取的专用线程.当数据到达时,我生成一个事件并传递数据进行处理.冲洗并重复.

The BinaryReader is used on a dedicated thread that does a blocking read. When data arrives I generate an event and pass the data for processing. Rinse and repeat.

BinaryWriter 在数据到达另一个线程时使用.现在它恰好是 UI 线程,但它不一定是.已知的一件事是它不会是阻塞读取器正在运行的同一个线程.

The BinaryWriter is used when data arrives on another thread. Right now it happens to be the UI thread, but it doesn’t have to be. One thing that is known is that it won’t be the same thread that the blocking reader is running.

一次只有一个进程会访问任一流处理程序,因此我不必担心两个线程同时访问 BinaryWriter,但会添加锁定.

Only one process will access either stream handler at a time so I don’t have to worry about two threads hitting the BinaryWriter at once, but locking will be added.

这是可行的,但由于线程很难,我不想假设这是合理的设计.我还有其他关于他们生命周期的问题,将单独提出.

This is working, but since threading is hard I don’t want to just assume this is sound design. I have other questions concerning the lifetimes of them that will be asked separately.

推荐答案

很不清楚,总是贴一个片段.如果他们包装了您从 TcpClient.GetStream() 获得的 NetworkStream,则没有问题.在 NetworkStream 的 MSDN 文章中明确提到:

Pretty unclear, always post a snippet. If they wrap the NetworkStream you get from TcpClient.GetStream() then there is no problem. Explicitly mentioned in the MSDN article for NetworkStream:

可以在 NetworkStream 类的实例上同时执行读写操作,无需同步.只要有一个唯一的写操作线程和一个唯一的读操作线程,就不会出现读写线程的交叉干扰,也不需要同步.

Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.

这篇关于在不同的线程中使用从同一流源派生的 BinaryReader 和 BinaryWriter 是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆