加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 可以在同一个Stream上启动多个异步读/写操作会破坏数据吗

发布时间:2020-12-15 08:31:36 所属栏目:百科 来源:网络整理
导读:我正在使用异步I / O,因为它不会阻塞调用线程并在幕后执行线程处理.如果我在同一个Stream上调用多个异步操作(如BeginWrite()),我是否需要担心数据缓冲区内容是否混合在一起? 我们假设我想发送3个缓冲区: Buffer1: 2222222222Buffer2: 2222222222Buffer3: 3
我正在使用异步I / O,因为它不会阻塞调用线程并在幕后执行线程处理.如果我在同一个Stream上调用多个异步操作(如BeginWrite()),我是否需要担心数据缓冲区内容是否混合在一起?

我们假设我想发送3个缓冲区:

Buffer1: 2222222222
Buffer2: 2222222222
Buffer3: 3333333333

我不介意缓冲区是否以错误的顺序发送,所以

333333333322222222222222222222

没问题,但缓冲内容是否可能完全混合在一起?

122213121212122333313111223333

PS:我100%肯定有人已经以某种形式问过这个……

解决方法

这取决于Stream的实现.例如,套接字支持读取和写入的多个重叠请求,文件API也是如此.它们保证每个操作的一致性(没有交错内容)以及操作顺序:例如,对于套接字读取,接收的字节将被放置在发布的订单中发布的缓冲区中.如果不提供这些保证,则无法编写高性能网络应用程序,因为需要重叠发送,但高性能网络IO实际上需要重叠接收.许多文章都描述了这种行为,包括good ole’ Windows Sockets 2.0: Write Scalable Winsock Apps Using Completion Ports,并记录在MSDN Overlapped Input/Output上:

Both send and receive operations can
be overlapped. The receive functions
may be invoked multiple times to post
receive buffers in preparation for
incoming data,and the send functions
may be invoked multiple times to queue
up multiple buffers to be sent. Note
that while a series of overlapped send
buffers will be sent in the order
supplied,the corresponding completion
indications may occur in a different
order. Likewise,on the receiving
side,buffers will be filled in the
order they are supplied,but
completion indications may occur in a
different order.

毫不奇怪,同样的保证会延续到世界的管理方面,例如. 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.

话虽这么说,在Stream上随机抛出异步读写会很快导致混乱.应用程序需要仔细协调线程提交操作的顺序,以使订单具有确定性.通常这意味着在保持同步锁的同时特别注意在(同步)列表中进行记帐以执行异步操作调用.

最后要注意的是,所有这些异步API都在特别说明,确保完成顺序不能保证与提交顺序相匹配.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读