Cancel call to 'HttpClient.SendAsync()'

旧街凉风 提交于 2019-12-29 08:04:50

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/29586743/cancel-call-to-httpclient-sendasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!