.NET TcpClient/NetworkStream implementation that supports async operations and respects timeouts

孤者浪人 提交于 2019-12-10 05:16:25

问题


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.

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?


回答1:


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.

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.

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



来源:https://stackoverflow.com/questions/10930052/net-tcpclient-networkstream-implementation-that-supports-async-operations-and-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!