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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…