如何等待多个异步HTTP请求

编程入门 行业动态 更新时间:2024-10-08 04:29:27
本文介绍了如何等待多个异步HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想问一下如何等待多个异步http请求.

I'd like to ask about how to wait for multiple async http requests.

我的代码是这样的:

public void Convert(XDocument input, out XDocument output) { var ns = input.Root.Name.Namespace; foreach (var element in input.Root.Descendants(ns + "a")) { Uri uri = new Uri((string)element.Attribute("href")); var wc = new WebClient(); wc.OpenReadCompleted += ((sender, e) => { element.Attribute("href").Value = e.Result.ToString(); } ); wc.OpenReadAsync(uri); } //I'd like to wait here until above async requests are all completed. output = input; }

有人知道这个的解决方案吗?

Dose anyone know a solution for this?

推荐答案

有一个文章由Scott撰写Hanselman 在其中描述了如何执行非阻塞请求.滚动到末尾,有一个 public Task< bool>.ValidateUrlAsync(string url)方法.

There is an article by Scott Hanselman in which he describes how to do non blocking requests. Scrolling to the end of it, there is a public Task<bool> ValidateUrlAsync(string url) method.

您可以像这样修改它(在响应阅读方面可能会更强大)

You could modify it like this (could be more robust about response reading)

public Task<string> GetAsync(string url) { var tcs = new TaskCompletionSource<string>(); var request = (HttpWebRequest)WebRequest.Create(url); try { request.BeginGetResponse(iar => { HttpWebResponse response = null; try { response = (HttpWebResponse)request.EndGetResponse(iar); using(var reader = new StreamReader(response.GetResponseStream())) { tcs.SetResult(reader.ReadToEnd()); } } catch(Exception exc) { tcs.SetException(exc); } finally { if (response != null) response.Close(); } }, null); } catch(Exception exc) { tcs.SetException(exc); } return tsc.Task; }

因此,您可以像这样使用它

So with this in hand, you could then use it like this

var urls=new[]{"url1","url2"}; var tasks = urls.Select(GetAsync).ToArray(); var completed = Task.Factory.ContinueWhenAll(tasks, completedTasks =>{ foreach(var result in completedTasks.Select(t=>t.Result)) { Console.WriteLine(result); } }); completed.Wait(); //anything that follows gets executed after all urls have finished downloading

希望这会使您朝着正确的方向前进.

Hope this puts you in the right direction.

PS.这可能很清楚,而无需使用async/await

PS. this is probably as clear as it can get without using async/await

更多推荐

如何等待多个异步HTTP请求

本文发布于:2023-11-26 10:26:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633690.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!