NetworkStream.ReadAsync with a cancellation token never cancels

前端 未结 6 1079
天涯浪人
天涯浪人 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条回答
  •  猫巷女王i
    2020-11-27 04:43

    There are a few problems there that pop out:

    1. CancellationToken throws OperationCanceledException, not TimeoutException (cancellation is not always due to timeout).
    2. ReceiveTimeout doesn't apply, since you're doing an asynchronous read. Even if it did, you'd have a race condition between IOException and OperationCanceledException.
    3. Since you're synchronously connecting the socket, you'll want a high timeout on this test (IIRC, the default connection timeout is ~90 seconds, but can be changed as Windows monitors the network speeds).
    4. The correct way to test asynchronous code is with an asynchronous test:

      [TestMethod]
      public async Task TestTest()
      {
          var tcp = new TcpClient() { ReceiveTimeout = 5000, SendTimeout = 20000 };
          tcp.Connect(IPAddress.Parse("176.31.100.115"), 25);
          await Read(tcp.GetStream());
      }
      

提交回复
热议问题