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.
source share