代码之家  ›  专栏  ›  技术社区  ›  dododo

NetworkStream.ReadTimeout工作不准确?

  •  0
  • dododo  · 技术社区  · 4 年前

    我在用 System.Net.Sockets.NetworkStream 与我的服务器应用程序对话。 初始化:

    var socket = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    socket.IOControl(IOControlCode.KeepAliveValues, keepAliveBytes, null); //where bytes are calculated based on OnOff = 1, KeepAliveTime = 120000,KeepAliveInterval = 10000
    socket.Connect(server_endpoint);
    socket.NoDelay = true;
    socket.ReceiveBufferSize = /*65kb*/; 
    socket.SendBufferSize = /*65kb*/;
    
    var stream = new NetworkStream(socket, true);
    stream.ReadTimeout = 750; // I expect triggering exception each time when this value is exceeded
    // Configure 1000 ms delay on the server side
    stream.ReadBytes(messageSizeBytes, 0, 4, cancellationToken); // I expect IOException here since the ReadTimeout is 750 but the server delay was 1000
    

    但有时它不会发生。我跟你核实过了 stopwatch :

    Stopwatch stop = Stopwatch.StartNew();
    _stream.ReadBytes(messageSizeBytes, 0, 4, cancellationToken);
    stop.Stop();
    

    1. The whole stream.ReadBytes duration => 1001.8625
    2. The configured ReadTimeout in this line => 750
    3. The exceeded time (without exception) => 1001.8625 - 750 = 251.8625
    

    所以,我的问题是,这是否是预期的,如果不是,为什么会存在这种情况?

    0 回复  |  直到 4 年前