runtime: Cannot access a disposed object. Object name: 'SslStream'.

I have an issue with SendAsync in .NET Core 2.2. When doing a lot of requests, I encounter the exception on some of them. I have gotten the error on different requests, for example on a small GET request. However I do have to mention that asynchronously I’m also doing other requests, for example POST (with content smaller than 4MB).

This issue is similar to https://github.com/dotnet/corefx/issues/34033 , but not the same. Mine doesn’t mention the handshake in the stacktrace and the other one should be fixed since Core 2.1 (and I use 2.2).

The operation was canceled.
   at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   at [details of own code omitted]

Inner exception:
The read operation failed, see inner exception.
   at System.Net.Security.SslStreamInternal.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer)
   at System.Net.Http.HttpConnection.FillAsync()
   at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean foldedHeadersAllowed)
   at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)

Inner Exception:
Cannot access a disposed object.
Object name: 'SslStream'.
   at System.Net.Security.SslState.ThrowIfExceptional()
   at System.Net.Security.SslState.CheckThrow(Boolean authSuccessCheck, Boolean shutdownCheck)
   at System.Net.Security.SslStreamInternal.ReadAsyncInternal[TReadAdapter](TReadAdapter adapter, Memory`1 buffer)

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 10
  • Comments: 31 (24 by maintainers)

Commits related to this issue

Most upvoted comments

I would say based on this stack trace, the only part we need to fix is the ‘ObjectDisposedException’. We should be able to detect when the SslStream is being closed by upstack code (in this case due to a cancellation) and prevent SslStream from accessing its own objects while closing down.

Nice catch. We have code in place trying to handle this race condition: https://github.com/dotnet/runtime/blob/cc74292fb04d03b4fc91df200fab3da50654d64a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/ChunkedEncodingReadStream.cs#L402-L414

But CancellationTokenSource.Register hands back a non-initialized registration if the token was already cancelled, and we’re passing around the registration instead of the token, so the above logic just no-ops instead in this case.

Another case where this check may fail is if the cancellation token passed to Read* methods changes. We have a race condition where:

  • the first read succeeds, but the cancellation fires before we dispose the registration.
  • the second read uses a different cancellation token and tries to hand back the connection. The checks all no-op since the token isn’t cancelled, and we return a disposed connection.

or a similar case where the second read happens as part of DrainAsync.


Solution-wise, we should ideally fix the underlying cause for all of this, which is using RegisterCancellation to dispose the stream instead of flowing the cancellation token around to ReadAsync/WriteAsync calls. I think this would be simpler and easier to reason about.

Otherwise your proposed solution nr. 2 seems better. With nr. 1 you wouldn’t catch the other variations of this race conditions I mentioned.

This is a connection pooling bug where a disposed (canceled) connection is returned to the pool and picked up by the next request in the queue. (And that request fails with an HttpRequestException --> ObjectDisposedException, since there is no cancellation occuring during its’ processing.)

In the case I managed to reproduce I see this happening in ChunkedEncodingReadStream.CopyToAsyncCore, but I think other code paths may also have the the same flaw:

  • cancelationToken is canceled at the moment the method is entered
  • RegisterCancelation runs the cancelation callback inline disposing the connection and the underlying stream. Since no OperationCanceledException is thrown, the execution of the method continues.
  • The response bytes are buffered already, the request can be fully served despite the cancellation. Calls to ReadChunkFromConnectionBuffer will parse out the response without touching the connections’ stream.
  • The last call to ReadChunkFromConnectionBuffer eventually calls HttpConnection.CompleteResponse, which returns the connection to the pool since there are no guards against _disposed on that path.

I see two simple fixes to this bug:

  1. Make sure that RegisterCancellation (its’ call sites) throw a TaskCanceledException in case of inline cancelations aborting any further processing logic that may call CompleteResponse. Note that we don’t have to throw here if we don’t want to since the data might be buffered.
  2. Acknowledge that calling CompleteResponse doesn’t guarantee the connection is alive. Do not return it to the pool if it’s _disposed.

It’s thus no surprise that this sometimes raises ObjectDisposedExceptions.

It seems like HttpClient should catch that exception and it should silently discard it if cancellation was requested

We have a mechanism to wrap these exceptions in OperationCanceledException where we first check the exception and the token with ShouldWrapInOperationCanceledException:

https://github.com/dotnet/runtime/blob/c9af66ccb24faea7538b682e4d928557276d7367/src/libraries/System.Net.Http/src/System/Net/Http/CancellationHelper.cs#L19-L20

Then we wrap the exception to a TaskCanceledException:

https://github.com/dotnet/runtime/blob/c9af66ccb24faea7538b682e4d928557276d7367/src/libraries/System.Net.Http/src/System/Net/Http/CancellationHelper.cs#L26-L27

We use this mechanism excessively in code that deals with the mentioned CancellationTokenRegistration-s, so I would assume that it’s either leaky or the ODE is caused by something else than cancellation.

Triage: We should see if we can detect it and avoid throwing. If not, then it is likely confusing to customers, in which case we may want to mask it / not include as inner exception of TaskCanceled.

Note: We have seen more customers running into this and being confused in the past.