Socket编程:发送和读取的异步方法能否保证数据的顺序?
如果我连续调用c#异步方法如下所示:
socket.BeginSend(data1, 0, data1.Length, 0,
new AsyncCallback(SendCallback1), handler);
socket.BeginSend(data2, 0, data2.Length, 0,
new AsyncCallback(SendCallback2), handler);
异步方法能保证数据的顺序吗?
其他支持异步操作的网络库是否考虑了这个问题?
它们内部是如何实现保证异步操作的数据顺序的?
If I call the c# asynchronous method continuously as shown below:
socket.BeginSend(data1, 0, data1.Length, 0,
new AsyncCallback(SendCallback1), handler);
socket.BeginSend(data2, 0, data2.Length, 0,
new AsyncCallback(SendCallback2), handler);
Can asynchronous method ensure the order of data?
Are other network Libraries that support asynchronous operation considered the problem?
how are they implemented to guarantee the data order in asynchronous operation internally?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,我不认为异步方法可以保证您发送的数据将按顺序发送或调用或发送。
正如 Marc 所说,即使它确实有效,请注意这不是正确的方法,您不应该并排或相继调用两个 BeginSend。您可以做的是在第一个 BeginSend 的回调方法中调用 EndSend,然后在该回调中调用下一个 BeginSend。
这是一篇关于该主题的很好的 MSDN 文章,请在继续之前先阅读它
No I don't think that asynchronous method would guarantee that the data you are sending will be sent in order or calling or sending.
As Marc said even if it does work note this is not the right approach, you should not call two BeginSend side by side or one after another. What you can do is call EndSend in the call back method of first BeginSend and then inside that callback call the next BeginSend.
This is a nice MSDN article on the topic read it first before moving forward
通常,在调用 EndSend 之后,您只会在第一个回调中执行第二个 BeginSend。我实际上希望如果已经有一个不完整的 BeginSend 正在进行,库会抛出异常。但如果它不抛出 - 我怀疑顺序是否能得到保证(我怀疑是否能保证成功)。
您还可以考虑异步 CTP,它具有此类操作的延续,允许您“等待”发送,然后作为延续执行额外的工作。
Normally you would only do the second BeginSend inside the callback from the first, after calling EndSend. I would actually hope the library would throw an exception if there was already an incomplete BeginSend in progress. But if it doesn't throw - I doubt order would be guaranteed (I doubt success would be guaranteed either).
You might also consider the async CTP which has continuations for this sort of thing, allowing you to "await" a send and then perform the additional work as a continuation.