问题
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