>我正在尝试从网络上读取RSS提要,并将其结果放入数组中。不幸的是,我已经在网上呆了 2 天,搜索每个解决方案,但没有成功。
在 Windows Phone 开发人员站点的示例中:
private void loadFeedButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new System.Uri("http://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx"));
}
// Event handler which runs after the feed is fully downloaded.
private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(e.Error.Message);
});
}
else
{
this.State["feed"] = e.Result;
UpdateFeedList(e.Result);
}
}
// This method sets up the feed and binds it to our ListBox.
private void UpdateFeedList(string feedXML)
{
StringReader stringReader = new StringReader(feedXML);
XmlReader xmlReader = XmlReader.Create(stringReader);
SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
feedListBox.ItemsSource = feed.Items;
loadFeedButton.Content = "Refresh Feed";
});
}
您可以看到"button_click"事件结束,当它继续进入 FinishDownload 事件,然后将结果放入 feedListBox 项源时。
现在,我不想要它。我想将结果放入列表或任何类似的 ADT 中
public static [ADT] Execute (string link)
{ .... }
以便此函数从提要中返回结果。
现在我正在尝试任何东西,线程和XDocument,但它不起作用。
因此,如果我理解正确,您想下载提要,然后只将项目放在列表、数组或类似物中而不是列表框中?然后你可以简单地添加以下行:
var feedItems = new List<SyndicationItem>(feed.Items);
我也觉得您希望在一个函数中全部使用,然后您可以使用任务以这种方式做到这一点:
public static Task<List<SyndicationItem>> Execute(string link)
{
WebClient wc = new WebClient();
TaskCompletionSource<List<SyndicationItem>> tcs = new TaskCompletionSource<List<SyndicationItem>>();
wc.DownloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
StringReader stringReader = new StringReader(e.Result);
XmlReader xmlReader = XmlReader.Create(stringReader);
SyndicationFeed feed = SyndicationFeed.Load(xmlReader);
tcs.SetResult(new List<SyndicationItem>(feed.Items));
}
else
{
tcs.SetResult(new List<SyndicationItem>());
}
};
wc.DownloadStringAsync(new Uri(link, UriKind.Absolute));
return tcs.Task;
}
然后,按钮的事件处理程序将是:
private async void loadFeedButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
var rssItems = await Execute("http://windowsteamblog.com/windows_phone/b/windowsphone/rss.aspx");
MessageBox.Show("Number of RSS items: " + rssItems.Count);
}
请注意 async 和 await 关键字,您可以在文档中阅读有关它们的更多信息。