Skip to content

Commit

Permalink
Merge pull request #208 from AArnott/workaroundCrash
Browse files Browse the repository at this point in the history
Avoid crashing .NET Core processes while canceling async I/O
  • Loading branch information
AArnott authored Jul 24, 2020
2 parents c0b15bb + b248f40 commit a240ca4
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/Nerdbank.Streams/PipeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,21 @@ private static PipeReader UsePipeReader(this Stream stream, int sizeHint = 0, Pi
// we can return a decorated PipeReader that calls us from its Complete method directly.
var combinedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
#pragma warning disable CS0618 // Type or member is obsolete
pipe.Writer.OnReaderCompleted((ex, state) => ((CancellationTokenSource)state).Cancel(), combinedTokenSource);
pipe.Writer.OnReaderCompleted(
(ex, state) =>
{
try
{
((CancellationTokenSource)state).Cancel();
}
catch (AggregateException cancelException)
{
// .NET Core may throw this when canceling async I/O (https://github.com/dotnet/runtime/issues/39902).
// Just swallow it. We've canceled what we intended to.
cancelException.Handle(x => x is ObjectDisposedException);
}
},
combinedTokenSource);

// When this argument is provided, it provides a means to ensure we don't hang while reading from an I/O pipe
// that doesn't respect the CancellationToken. Disposing a Stream while reading is a means to terminate the ReadAsync operation.
Expand Down

0 comments on commit a240ca4

Please sign in to comment.