C# 带有一个回调的多个异步 HttpRequest
我想一次发出 10 个异步 http 请求,并且仅在所有请求完成后并在单个回调函数中处理结果。我也不想使用 WaitAll 阻塞任何线程(据我所知,WaitAll 会阻塞直到所有线程完成)。我想我想制作一个自定义 IAsyncResult 来处理多个调用。我走在正确的轨道上吗?是否有任何好的资源或示例来描述处理此问题?
I want to make 10 asynchronous http requests at once and only process the results when all have completed and in a single callback function. I also do not want to block any threads using WaitAll (it is my understanding that WaitAll blocks until all are complete). I think I want to make a custom IAsyncResult which will handle multiple calls. Am I on the right track? Are there any good resources or examples out there that describe handling this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我喜欢达林的解决方案。但是,如果你想要更传统的东西,你可以尝试这个。
我肯定会使用等待句柄数组和 WaitAll 机制:
I like Darin's solution. But, if you want something more traditional, you can try this.
I would definitely use an array of wait handles and the WaitAll mechanism:
在 .NET 4.0 中,有一个很好的并行任务库 允许您执行以下操作:
正如您所看到的,对于列表中的每个 url,都会启动不同的任务,一旦所有任务完成,就会调用回调并传递所有任务的结果。
In .NET 4.0 there's a nice parallel Task library that allows you to do things like:
As you can see for each url in the list a different task is started and once all tasks are completed the callback is invoked and passed the result of all tasks.
我认为你最好使用 WaitAll 方法。否则,您将处理 10 个 IAsyncResult 回调,并使用信号量确定所有 10 个回调最终完成。
请记住,WaitAll 非常高效;它不像线程“睡眠”那样愚蠢。当线程休眠时,它会继续使用处理时间。当线程因为命中 WaitAll 而被“取消调度”时,该线程将不再消耗任何处理器时间。这是非常有效的。
I think you are better off using the WaitAll approach. Otherwise you will be processing 10 IAsyncResult callbacks, and using a semaphore to determine that all 10 are finally complete.
Keep in mind that WaitAll is very efficient; it is not like the silliness of having a thread "sleep." When a thread sleeps, it continues to use processing time. When a thread is "de-scheduled" because it hit a WaitAll, then the thread no longer consumes any processor time. It is very efficient.