Skip to content

Commit 37151f8

Browse files
authored
Preserve OCE.CancellationToken in StreamPipeReader (#82745)
1 parent 4862343 commit 37151f8

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeReader.cs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -262,11 +262,16 @@ static async ValueTask<ReadResult> Core(StreamPipeReader reader, CancellationTok
262262
reader._isStreamCompleted = true;
263263
}
264264
}
265-
catch (OperationCanceledException)
265+
catch (OperationCanceledException ex)
266266
{
267267
reader.ClearCancellationToken();
268268

269-
if (tokenSource.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
269+
if (cancellationToken.IsCancellationRequested)
270+
{
271+
// Simulate an OCE triggered directly by the cancellationToken rather than the InternalTokenSource
272+
throw new OperationCanceledException(ex.Message, ex, cancellationToken);
273+
}
274+
else if (tokenSource.IsCancellationRequested)
270275
{
271276
// Catch cancellation and translate it into setting isCanceled = true
272277
isCanceled = true;
@@ -275,7 +280,6 @@ static async ValueTask<ReadResult> Core(StreamPipeReader reader, CancellationTok
275280
{
276281
throw;
277282
}
278-
279283
}
280284

281285
return new ReadResult(reader.GetCurrentReadOnlySequence(), isCanceled, reader._isStreamCompleted);

src/libraries/System.IO.Pipelines/tests/StreamPipeReaderTests.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,9 @@ public async Task ReadCanBeCancelledViaProvidedCancellationToken()
263263

264264
stream.WaitForReadTask.TrySetResult(null);
265265

266-
await Assert.ThrowsAsync<OperationCanceledException>(async () => await task);
266+
var oce = await Assert.ThrowsAsync<OperationCanceledException>(async () => await task);
267+
Assert.Equal(cts.Token, oce.CancellationToken);
268+
Assert.IsType<OperationCanceledException>(oce.InnerException);
267269
reader.Complete();
268270
}
269271

0 commit comments

Comments
 (0)