简体   繁体   English

C#-同时HttpWebRequest以获取服务器的响应

[英]C# - Simultaneous HttpWebRequest in order to get a response from server

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. 我目前正在作为我的项目来开发C#下载管理器(WinForms),但遇到了一个问题,我不确定最好的方法是什么。

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. 例如,我要从Web服务器检索信息。 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. 相反,我将等待2秒,然后发送另一个请求,然后再发送另一个请求,直到其中一个被应答为止。

  1. Am I entirely wrong with this re-sending approach? 我对这种重新发送方法完全错误吗? Should I just send one request and wait for a response? 我应该只发送一个请求并等待响应吗?

  2. 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. 非常感谢您的帮助。

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. 但这只是我的意见...所有这些只是我的意见...我认为是正确的。

If your using .Net 4.0, you can try the parallel processing. 如果您使用的是.Net 4.0,则可以尝试并行处理。 Something like this: 像这样:

Parallel.ForEach(ListOfRequest, req => {
     // Retrive information from a web server.
});

Or you can checkout this link for your token thing cancellation for job: Parallel Programming: Task Cancellation 或者,您也可以签出此链接以取消作业的令牌性事物: 并行编程:任务取消

Hope this help, thanks. 希望有帮助,谢谢。

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

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