C# - 同步 HttpWebRequest 以从服务器获取响应
我目前正在开发一个 C# 下载管理器 (WinForms) 作为我的一个项目,我遇到了一个问题,我不确定最好的方法是什么。
我想在最佳时间“强制”网络服务器做出响应。考虑到这一点,我认为最好以一定的时间间隔重复发送请求,直到其中一个请求得到答复。假设服务器响应良好,这应该会消除一些延迟。
例如, 我想从网络服务器检索信息。我不想发送请求并等待它超时然后重新发送。相反,我会等待 2 秒钟,然后发送另一个请求,然后再发送另一个请求,直到其中一个请求得到答复。
我这种重新发送的方法完全错误吗?我应该只发送一个请求并等待响应吗?
对此有什么好的解决方案吗?使用具有相同取消令牌的多个任务? 带信号的异步请求?
非常感谢您的帮助。
I'm currently working on a C# download manager (WinForms) as a project of mine and I've faced a problem which I'm not sure what the best approach would be.
I want to 'force' a response from a web server at optimal time. Having that in mind, I figured it would be best to send requests repeatedly with a certain interval until one of the requests is answered. Assuming the server is responsive, this should eliminate some of the delay.
For example,
I want to retrieve information from a web server. I don't want to send a request and wait for it to timeout and then re-send. Instead I would wait 2 seconds and send another request and then another until one of them is answered.
Am I entirely wrong with this re-sending approach? Should I just send one request and wait for a response?
What would be a good solution for this? Using several Tasks with the same cancellation token?
Asynchronous requests with a signal?
Would very much appreciate your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我认为大多数下载管理器都会并行化正在下载的文件片段......而不完全是下载的启动。我认为你不应该关心强制快速响应,实际上我认为这没有帮助。
当您发出请求时,它会找到到服务器的路由,然后再返回。一旦你知道了路线,下一次就会很快......也就是说,如果你使用很多线程发出多个请求,所有这些请求可能会同时得到答复,因为路线尚未确定发现”,一旦发现,所有这些都将使用相同的路径。
至于如何做到这一点......我会使用异步请求来做到这一点。
但这只是我的意见……这一切都只是我的意见……我认为是正确的。
Well, I think that most of the download managers parallelize pieces of the file being downloaded... not exactly the startup of the download. I don't think you should care about forcing a fast response, actually I think it won't help.
When you make a request it is going to find it's route to the server and then back again. Once you know the route, the next time is going to be fast... that is, if you make multiple requests using a lot of threads, all of them will probably be answered at the same time, because the route is yet being 'discovered', and once it is discovered all of them will use the same path.
As matter of how to do it... I would do it using asynchronous requests.
But that is only my opinion... that is all of this is just my opinion... just what I think is true.
如果您使用.Net 4.0,您可以尝试并行处理。
像这样的事情:
或者您可以查看此链接以取消工作的令牌:
并行编程:任务取消
希望有帮助,谢谢。
If your using .Net 4.0, you can try the parallel processing.
Something like this:
Or you can checkout this link for your token thing cancellation for job:
Parallel Programming: Task Cancellation
Hope this help, thanks.