Is it possible to cancel a call to HttpClient.SendAsync()
?
I'm sending some data like this:
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "some url");
var multipartFormDataContent = new MultipartFormDataContent();
// ... construction of the MultipartFormDataContent. It contains form data + picture file
requestMessage.Content = multipartFormDataContent;
var response = await client.SendAsync(requestMessage).ConfigureAwait(false);
This code works perfectly, but I need to be able to cancel a request on user demand. Is this possible?
I see that there is an overload of SendAsync
that accepts a CancellationToken
but I don't know how to use it. I also know about a property called IsCancellationRequested
that indicates if a request has been canceled. But how do I go about actually canceling a request?
The SendAsync
method supports cancellation. You can use the overload which takes a CancellationToken
, which can be canceled any time you like.
You need to use the CancellationTokenSource
class for this purpose. The following code shows how to do that.
CancellationTokenSource tokenSource = new CancellationTokenSource();
...
var response = await client.SendAsync(requestMessage, tokenSource.Token)
.ConfigureAwait(false);
When you want to cancel the request, call tokenSource.Cancel();
and you're done.
Important: There is no guarantee that cancelling the CancellationTokenSource
will cancel the underlying operation. It depends upon the implementation of the underlying operation (in this case the SendAsync
method). The operation could be canceled immediately, after few seconds, or never.
It is worth noting that this is how you'd cancel any method which supports CancellationToken
. It will work with any implementation, not just the SendAsync
method that is the subject of your question.
For more info, refer to Cancellation in Managed Threads