取消呼叫'HttpClient.SendAsync() [英] Cancel call to 'HttpClient.SendAsync()'

查看:857
本文介绍了取消呼叫'HttpClient.SendAsync()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能取消 HttpClient.SendAsync()

我要送些这样的数据:

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?

我看到有一个的 SendAsync 的超负荷接受的CancellationToken 但我不知道如何使用它。我还知道一个叫 IsCancellationRequested 属性,指示如果请求已被取消。但这样做我怎么去真正取消的请求?

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?

推荐答案

SendAsync 方法支持取消。您可以使用它接受过载的CancellationToken ,可以取消任何你喜欢的时间。

The SendAsync method supports cancellation. You can use the overload which takes a CancellationToken, which can be canceled any time you like.

您需要使用 CancellationTokenSource 类用于此目的。 。下面的代码演示如何做到这一点。

You need to use the CancellationTokenSource class for this purpose. The following code shows how to do that.

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

当您要取消请求,调用 tokenSource.Cancel(); 键,你就大功告成了。

When you want to cancel the request, call tokenSource.Cancel(); and you're done.

重要提示:有没有保证,取消 CancellationTokenSource 将取消基础操作。它取决于底层操作的实现(在这种情况下,在 SendAsync 方法)。操作可以立即取消,几秒钟,或者从未之后。

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.

值得注意的是,这是你如何取消的任何的方法它支持的CancellationToken 。它会与任何的实现工作,而不仅仅是那是你的问题的主题 SendAsync 方法。

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

这篇关于取消呼叫'HttpClient.SendAsync()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆