Unhandled `AggregateException` caused by `StreamPipeWriter.FlushInternalAsync`

Open
#112,651 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
48/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Quiet
Tech stack
csharp
Domain
backend

Research direction

Start by reading StreamPipeWriter.FlushAsyncInternal in src/libraries/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs, especially the cancellation-token registration mentioned in the issue. Run the linked reproduction repository to observe disposing the writer during an in-progress write. Done means that disposal no longer causes an unhandled exception and the write reports an exception as expected.

Written by the indexing model from the issue text.

Description

area-System.IO.Pipelines untriaged
Description

Disposing a StreamPipeWriter while StreamPipeWriter.FlushAsyncInternal is in progress may cause an AggregateException to be thrown in .NET code. This exception is thrown from a call stack which is only executing .NET runtime code, which means we can't catch it and it crashes the application.

This is the full exception from our crash logs:

System.AggregateException: One or more errors occurred. (The CancellationTokenSource has been disposed.)
 ---> System.ObjectDisposedException: The CancellationTokenSource has been disposed.
   at System.Threading.CancellationTokenSource.Cancel()
   at System.Threading.CancellationTokenSource.CallbackNode.ExecuteCallback()
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
   --- End of inner exception stack trace ---
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
   at System.Threading.TimerQueueTimer.Fire(Boolean isThreadPool)
   at System.Threading.TimerQueue.FireNextTimers()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading.PortableThreadPool.WorkerThread.WorkerThreadStart()
Reproduction Steps

Using this repository (ignore "websocket" in the name, I narrowed the issue down further after creating the repo): https://github.com/gmcchessney/dotnet-websocket-crash

// This is just a stream that has a Thread.Sleep in the overridden Write method.
using SlowNullStream myStream = new();

// Concrete type is StreamPipeWriter
PipeWriter myPipeWriter = PipeWriter.Create(myStream);
var pipeWriterStream = myPipeWriter.AsStream();
var bytes = Encoding.UTF8.GetBytes("Hello, World!");

CancellationTokenSource myCts = new(TimeSpan.FromSeconds(1));

// This write will take at least ten seconds because of SlowNullStream
var writeTask = pipeWriterStream.WriteAsync(bytes, myCts.Token);

// Dispose while a write is in progress, and before the cancellation
// token is canceled. The application will crash when the
// CancellationTokenSource is canceled by its cancellation timer.
pipeWriterStream.Dispose();

await writeTask;

Console.WriteLine("This won't happen because we've crashed!");
Expected behavior

An unhandled exception is not thrown. I would rather expect an exception to be thrown from the call to WriteAsync since the StreamPipeWriter is now disposed.

Actual behavior

An exception is thrown from a CancellationToken registration delegate. Since the CancellationTokenSource is canceled by an internal timer, the exception is unhandled and crashes the application.

Regression?

No response

Known Workarounds

Ensure no writes to the StreamPipeWriter are in progress when Dispose is called.

Configuration

.NET 8 and .NET 9 (tried both)
Windows 11 v10.0.26100
x64

I don't believe this issue has anything to do with my specific configuration.

Other information

The exception is thrown from the CancellationToken registration delegate set up in StreamPipeWriter.FlushAsyncInternal.

Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/runtime

All issues in dotnet/runtime

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.