传递 a CancellationToken
toReadAsync()
不会增加太多价值,因为它仅在 开始读取之前检查令牌的状态:
// 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<int>(cancellationToken)
: BeginEndReadAsync(buffer, offset, count);
您可以很容易地自己添加一个 timout 机制,方法是等待ReadAsync()
或 timout 任务完成,如下所示:
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}");
}