WebClient:如何取消长时间运行的 HTTP 请求?
我正在使用 WebClient 向一个运行时间很长的 API 发出请求。但我实际上不需要知道结果,我只需要开始这个过程。
该过程成功或失败对我来说并不重要。所以我想在发出请求后立即断开连接。
如何断开网络客户端的连接?我不想等待 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?
I'm using WebClient to make a request to an API that has a very long running process. 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? I don't want to wait 30 - 60 seconds for the response:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用:
client.CancelAsync()
You could use the:
client.CancelAsync()
CancelAsync()
应该可以解决问题。CancelAsync()
should do the trick.我建议您使用 DownloadProgressChanged 事件改为 =>您将确保服务器收到您的请求并开始处理它。
警告:如果情况并非如此,您还需要更新服务器代码,以便在启动进程后立即开始返回信息(HTTP 标头或某些文本)。如果没有,DownloadProgressChanged 仅在进程完成后才开始接收信息。
I suggest you to use DownloadProgressChanged event instead => you will be sure the server received your request and started to treat it.
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. If not, DownloadProgressChanged will start receiving information only when process is done.