假设我有下面的类:递归异步HttpWebRequests
Public class FooBar
{
List<Items> _items = new List<Items>();
public List<Items> FetchItems(int parentItemId)
{
FetchSingleItem(int itemId);
return _items
}
private void FetchSingleItem(int itemId)
{
Uri url = new Uri(String.Format("http://SomeURL/{0}.xml", itemId);
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
webRequest.BeginGetResponse(ReceiveResponseCallback, webRequest);
}
void ReceiveResponseCallback(IAsyncResult result)
{
// End the call and extract the XML from the response and add item to list
_items.Add(itemFromXMLResponse);
// If this item is linked to another item then fetch that item
if (anotherItemIdExists == true)
{
FetchSingleItem(anotherItemId);
}
}
}
有可能是任何数量的链接项目,我只知道在运行的。
我想要做的就是首先打电话给FetchSingleItem
,然后等到所有的呼叫都完成后再返回List<Items>
给调用代码。
有人能指出我在正确的方向?我很乐意重构整个事情,如果需要的话(我怀疑是这种情况!)
你为什么不使用WebClient.DownloadStringAsync? – AnthonyWJones 2011-03-25 22:14:56