除非您将多个任务链接在一起,否则这种特殊的重载基本上是无用的——cancellationToken
仅在进入ReadAsync
方法调用时检查,而不是在底层Stream.BeginRead
调用执行时检查。
从 ILSpy 转储的代码:
public virtual Task<int> ReadAsync(byte[] buffer,
int offset,
int count,
CancellationToken cancellationToken)
{
if (!cancellationToken.IsCancellationRequested)
return this.BeginEndReadAsync(buffer, offset, count);
return Task.FromCancellation<int>(cancellationToken);
}
如您所见,cancellationToken
不会转发到BeginEndReadAsync
呼叫中,而BeginEndReadAsync
只是按照以下方式实现Stream.BeginRead
:
private Task<int> BeginEndReadAsync(byte[] buffer, int offset, int count)
{
return TaskFactory<int>.FromAsyncTrim<Stream, Stream.ReadWriteParameters>(
this,
new Stream.ReadWriteParameters
{
Buffer = buffer,
Offset = offset,
Count = count
},
(Stream stream, Stream.ReadWriteParameters args, AsyncCallback callback, object state) =>
stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state),
(Stream stream, IAsyncResult asyncResult) =>
stream.EndRead(asyncResult)
);
}
此时,您拥有的唯一保证是派生流类型所做出的保证,这些类型因类型而异。
请注意,这是基于当前的 .Net 4.5 位,并且实现当然会在未来发生变化。