Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Hang on when GetRequestStreamAsync #113409

Merged
Original file line number Diff line number Diff line change
Expand Up @@ -1099,7 +1099,23 @@ private async Task<Stream> InternalGetRequestStream()
TaskCompletionSource<Stream> getStreamTcs = new();
TaskCompletionSource completeTcs = new();
_sendRequestTask = SendRequest(async: true, new RequestStreamContent(getStreamTcs, completeTcs));
_requestStream = new RequestStream(await getStreamTcs.Task.ConfigureAwait(false), completeTcs);
Task<Stream> getStreamTask = getStreamTcs.Task;
try
{
Task result = await Task.WhenAny(getStreamTask, _sendRequestTask).ConfigureAwait(false);
if (result == _sendRequestTask)
{
await _sendRequestTask.ConfigureAwait(false); // Propagate the exception
// If we successfully completed the request without getting the stream,
// return a null stream to avoid blocking.
return Stream.Null;
}
_requestStream = new RequestStream(await getStreamTask.ConfigureAwait(false), completeTcs);
}
catch (Exception ex)
{
throw WebException.CreateCompatibleException(ex);
}
}
else
{
Expand Down
9 changes: 9 additions & 0 deletions src/libraries/System.Net.Requests/tests/HttpWebRequestTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2094,6 +2094,15 @@ await server.AcceptConnectionAsync(async connection =>
});
}

[Fact]
public async Task SendHttpPostRequest_BufferingDisabledWithInvalidHost_ShouldThrow()
{
HttpWebRequest request = WebRequest.CreateHttp("http://anything-unusable-blabla");
request.Method = "POST";
request.AllowWriteStreamBuffering = false;
await Assert.ThrowsAnyAsync<WebException>(() => request.GetRequestStreamAsync());
}

[Fact]
public async Task SendHttpPostRequest_BufferingDisabled_ConnectionShouldStartWithRequestStream()
{
Expand Down
Loading