It seems that GetResponseAsync does not accept cancellationToken in Async/Await. So the question is how can I cancel the below procedure, provided I need to collect Cookies from response:
using (HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync())
{
cookies.Add(response.Cookies);
}
An alternative code to achieve the above is also welcome.
Something like this should work (untested):
In theory, if cancellation is requested on
ct
andrequest.Abort
is invoked,await request.GetResponseAsync()
should throw aWebException
. IMO though, it's always a good idea to check for cancellation explicitly when consuming the result, to mitigate race conditions, so I callct.ThrowIfCancellationRequested()
.Also, I assume that
request.Abort
is thread-safe (can be called from any thread), so I useuseSynchronizationContext: false
(I haven't verified that).[UPDATED] to address the OP's comment on how to differentiate between
WebException
caused by cancellation and any other error. This is how it can be done, soTaskCanceledException
(derived fromOperationCanceledException
) will be correctly thrown upon cancellation:Now you can use your cancellation token on any cancelable async method. For example WebRequest.GetResponseAsync:
will become:
See example http://pastebin.com/KauKE0rW