WebClient: how to cancel a long running HTTP request?

懵懂的女人 提交于 2021-02-18 19:22:05

问题


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?

回答1:


You could use the: client.CancelAsync()




回答2:


CancelAsync() should do the trick.




回答3:


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.



来源:https://stackoverflow.com/questions/7700483/webclient-how-to-cancel-a-long-running-http-request

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