NetworkStream.ReadAsync with a cancellation token never cancels

前端 未结 6 1078
天涯浪人
天涯浪人 2020-11-27 04:02

Here the proof.
Any idea what is wrong in this code ?

    [TestMethod]
    public void TestTest()
    {
        var tcp = new TcpClient() { ReceiveTimeou         


        
6条回答
  •  我在风中等你
    2020-11-27 04:47

    Cancellation is cooperative. NetworkStream.ReadAsync must cooperate to be able to be cancelled. It is kind of hard for it to do that because that would potentially leave the stream in an undefined state. What bytes have already been read from the Windows TCP stack and what haven't? IO is not easily cancellable.

    Reflector shows that NetworkStream does not override ReadAsync. This means that it will get the default behavior of Stream.ReadAsync which just throws the token away. There is no generic way Stream operations can be cancelled so the BCL Stream class does not even try (it cannot try - there is no way to do this).

    You should set a timeout on the Socket.

提交回复
热议问题