Cancel C# 4.5 TcpClient ReadAsync by timeout

前端 未结 4 512
北海茫月
北海茫月 2021-01-11 23:32

What would the proper way to cancel TcpClient ReadAsync operation by timeout and catch this timeout event in .NET 4.5?

TcpClient.ReadTimeout seems to be applied to

4条回答
  •  长情又很酷
    2021-01-11 23:51

    Passing a CancellationToken to ReadAsync() doesn't add much value because it checks the status of the token only before it starts reading:

    // If cancellation was requested, bail early with an already completed task.
    // Otherwise, return a task that represents the Begin/End methods.
    return cancellationToken.IsCancellationRequested
                ? Task.FromCanceled(cancellationToken)
                : BeginEndReadAsync(buffer, offset, count);
    

    You can quite easily add a timout mechanism yourself by waiting for either the ReadAsync() or the timout task to complete like this:

    byte[] buffer = new byte[128];
    TimeSpan timeout = TimeSpan.FromSeconds(30);
    
    var readTask = stream.ReadAsync(buffer, 0, buffer.Length);
    var timeoutTask = Task.Delay(timeout);
    await Task.WhenAny(readTask, timeoutTask);
    if (!readTask.IsCompleted)
    {
        throw new TimeoutException($"Connection timed out after {timeout}");
    }
    

提交回复
热议问题