Skip to content

Conversation

@grendello
Copy link
Contributor

The HttpURLConnection.ConnectAsync API doesn't accept a CancellationToken
instance and, thus, cannot be easily cancelled in a graceful manner. This
limitation resulted in using the Task.WhenAny to make sure the connection
attempt is aborted whenever the calling task is cancelled. This, however, led to
a problem of unobserved exceptions should the cancellation occur before the
connection attempt was successful.

This commit wraps the synchronous HttpURLConnection.Connect call in a task
that is passed the cancellation token, so that it can be gracefully cancelled
when needed. The cancellation is done by registering a handler for when token is
about to expire as Task.Run will check if cancellation was requested only before
it runs the passed code, the rest is the code's responsibility.
Since URLConnection.Connect() is asynchronous we abort it by calling
Disconnect() on the instance which is a brutal but effective way to interrupt
the connection attempt.

Additionally, the diff makes sure to properly configure a few tasks for await

Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=51804

The `HttpURLConnection.ConnectAsync` API doesn't accept a `CancellationToken`
instance and, thus, cannot be easily cancelled in a graceful manner. This
limitation resulted in using the `Task.WhenAny` to make sure the connection
attempt is aborted whenever the calling task is cancelled. This, however, led to
a problem of unobserved exceptions should the cancellation occur before the
connection attempt was successful.

This commit wraps the synchronous `HttpURLConnection.Connect` call in a task
that is passed the cancellation token, so that it can be gracefully cancelled
when needed. The cancellation is done by registering a handler for when token is
about to expire as Task.Run will check if cancellation was requested only before
it runs the passed code, the rest is the code's responsibility.
Since `URLConnection.Connect()` is asynchronous we abort it by calling
`Disconnect()` on the instance which is a brutal but effective way to interrupt
the connection attempt.

Additionally, the diff makes sure to properly configure a few tasks for `await`

Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=51804
@jonpryor jonpryor merged commit 9148150 into dotnet:d15-1 Mar 23, 2017
@grendello grendello deleted the d15-1 branch June 19, 2018 08:53
@github-actions github-actions bot locked and limited conversation to collaborators Feb 5, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants