fix race between request failure and response body read
authorGeoff Kizer <geoffrek>
Wed, 24 Jul 2019 20:58:28 +0000 (13:58 -0700)
committerGeoff Kizer <geoffrek>
Wed, 24 Jul 2019 20:58:28 +0000 (13:58 -0700)
Commit migrated from https://github.com/dotnet/corefx/commit/a327d792c1590bd9ef744c197dfbb311961d5eef

src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Stream.cs

index 9039453..a03e11d 100644 (file)
@@ -169,6 +169,10 @@ namespace System.Net.Http
                 {
                     if (NetEventSource.IsEnabled) Trace($"Failed to send request body: {e}");
 
+                    // Cancel the stream before we set _requestCompletionState below.
+                    // Otherwise, a response stream reader may race with the actual Cancel.
+                    Cancel();
+
                     lock (SyncObject)
                     {
                         Debug.Assert(_requestCompletionState == StreamCompletionState.InProgress, $"Request already completed with state={_requestCompletionState}");
@@ -177,8 +181,6 @@ namespace System.Net.Http
                         CheckForCompletion();
                     }
 
-                    Cancel();
-
                     throw;
                 }
 
@@ -291,7 +293,7 @@ namespace System.Net.Http
 
                 if (requestBodyCancellationSource != null)
                 {
-                    // When cancellation propagates, SendRequestBodyAsync will set _responseCompletionState to Failed
+                    // When cancellation propagates, SendRequestBodyAsync will set _requestCompletionState to Failed
                     requestBodyCancellationSource.Cancel();
                 }