Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

c# - Cancel call to 'HttpClient.SendAsync()'

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...