我想问一下如何等待多个异步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请求
发布评论