Cancel the call to "HttpClient.SendAsync ()"

Can I cancel the call to HttpClient.SendAsync() ?

I am sending some data as follows:

 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 fine, but I need to cancel the request at the user's request. Is it possible?

I see that there is a SendAsync overload that accepts a CancellationToken , but I don't know how to use it. I also know about a property called IsCancellationRequested , which indicates whether the request has been canceled. But how can I actually cancel the request?

+2
source share
1 answer

The SendAsync method supports cancellation. You can use an overload that accepts a CancellationToken , which can be canceled at any time convenient for you.

For this purpose you need to use the CancellationTokenSource class. The following code shows how to do this.

 CancellationTokenSouce tokenSource = new CancellationTokenSouce(); ... var response = await client.SendAsync(requestMessage, tokenSource.Token) .ConfigureAwait(false); 

If you want to cancel the request, call tokenSource.Cancel(); and everything will be ready.

Important : There is no guarantee that canceling a CancellationTokenSource cancel the underlying operation. It depends on the implementation of the main operation (in this case, the SendAsync method). The operation can be canceled immediately, in a few seconds or never.

It is worth noting that you can cancel any method that supports the CancellationToken . It will work with any implementation, not just the SendAsync tag, which is the subject of your question.

For more information, see Cancel in Managed Threads.

+6
source

Source: https://habr.com/ru/post/970013/


All Articles