How to cancel NetworkStream.ReadAsync without closing stream

后端 未结 3 1662
陌清茗
陌清茗 2020-12-17 15:52

I am trying to use NetworkStream.ReadAsync() to read data but I cannot find how to cancel the ReadAsync() once called. For background, the NetworkStream is provided to me b

3条回答
  •  温柔的废话
    2020-12-17 16:19

    You cannot cancel the ReadAsync since the internal call is unmanaged and uses IOCompletion ports.. Your options are as follows.

    1. Use Socket.Shutdown(). This will return ReadAsync with a socket error of OperationAborted.
    2. Wait for the read to timeout.
    3. Check if data is available before reading from the socket.

提交回复
热议问题