简体   繁体   English

WebClient:如何取消长时间运行的HTTP请求?

[英]WebClient: how to cancel a long running HTTP request?

I'm using WebClient to make a request to an API that has a very long running process. 我正在使用WebClient向一个运行时间很长的API发出请求。 But I don't actually need to know the result, I only need the process to be started. 但我实际上并不需要知道结果,我只需要启动该过程。

It doesn't matter to me if the process succeeds or fails. 如果过程成功或失败,对我来说无关紧要。 So I want to drop the connection as soon as I have made the request. 所以我想在我提出请求后立即放弃连接。

How can I drop the webclient's connection? 如何删除webclient的连接? I don't want to wait 30 - 60 seconds for the response: 我不想等待30-60秒的回复:

var client = new WebClient();
string url = "http://example.com/SomeVeryLongRunningProcess/parameter";
client.BeginDownloadString(uri);
client.DropConnection; // how do I drop the connection before the response is received?

你可以使用: client.CancelAsync()

CancelAsync()应该可以解决问题。

I suggest you to use DownloadProgressChanged event instead => you will be sure the server received your request and started to treat it. 我建议您使用DownloadProgressChanged事件而不是=>您将确保服务器收到您的请求并开始对其进行处理。

Warning: you also need to update your server code to start returning information (HTTP headers or some text) as soon as it starts the process if this is not the case. 警告:如果不是这种情况,您还需要更新服务器代码,以便在启动过程后立即开始返回信息(HTTP标头或某些文本)。 If not, DownloadProgressChanged will start receiving information only when process is done. 如果没有,DownloadProgressChanged将仅在进程完成时开始接收信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM