.NET的TcpClient /的NetworkStream实现,支持异步操作和尊重超时 [英] .NET TcpClient/NetworkStream implementation that supports async operations and respects timeouts

查看:402
本文介绍了.NET的TcpClient /的NetworkStream实现,支持异步操作和尊重超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据问题,论坛帖子等的数量,似乎在BCL中的TcpClient /的NetworkStream实施缺乏对取消IO操作不错的支持。由于增加了在.NET 4.5异步方法,这种没有取消(或体面的超时支持)使得事情变得更加令人沮丧,因为它变得更加复杂(几乎不可能),以取消拒绝监督,同时执行的IO它的CancellationToken任务

Based on the number of questions, forum posts, etc, it appears that the TcpClient/NetworkStream implementation in the BCL lacks decent support for cancelling IO operations. With the addition of Async methods in .NET 4.5, this lack of cancellation (or decent timeout support) makes things even more frustrating since it becomes even more complicated (nigh on impossible) to cancel a task that refuses to monitor its CancellationToken while performing IO.

我看到了许多实现,旋转起来额外的线程来监视网络运行并关闭底层流,如果事情似乎是想错了。这种感觉很肮脏的世界里,我们正在尝试使用异步操作来保护这些资源。

I have seen many implementations that spin up additional threads to monitor the network operation and close the underlying stream if things seem to be going wrong. This feels very dirty in a world where we're trying to conserve these resources by using async operations.

任何人都可以点我的指导方向,以应对有效地消除/超时网络IO操作或对一个强大的第三方实施的实际工作?

Can anyone point me in the direction of guidance as to dealing with efficiently cancelling/timing out network IO operations or towards a robust 3rd party implementation that actually works?

推荐答案

取消IO是不平凡的。与Vista开始,我们有CancelIO能力,但是这是一个相当新的事物和驱动程序需要支持它。

Cancelling IO is not trivial. Starting with Vista we have the CancelIO capability, but that is a fairly new thing and drivers need to support it.

实事求是地讲,最好你能做的就是关闭套接字取消一切。另外,可以实现围绕任务,提供即时完成时的CancellationToken成为集包装函数。 IO操作仍将继续,但其结果将被丢弃。

Practically speaking, the best you can do is close the socket to cancel everything. Alternatively, you can implement a wrapper function around a task which provides instant completion when the CancellationToken becomes set. The IO operation would still continue but its result would be discarded.

下面是对这个问题进行深入讨论:<一href="http://social.msdn.microsoft.com/Forums/da-DK/async/thread/54632b19-0e9c-4078-aa59-c4389e75b187" rel="nofollow">http://social.msdn.microsoft.com/Forums/da-DK/async/thread/54632b19-0e9c-4078-aa59-c4389e75b187

Here is a thorough discussion about the issue: http://social.msdn.microsoft.com/Forums/da-DK/async/thread/54632b19-0e9c-4078-aa59-c4389e75b187

这篇关于.NET的TcpClient /的NetworkStream实现,支持异步操作和尊重超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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