我正在尝试从网络上读取RSS源,并将其结果放入数组中。 不幸的是,我已经在网上呆了两天,寻找所有解决方案,但没有成功。
在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)
{ .... }
以便此函数返回Feed中的结果。
现在我正在尝试任何东西,线程和XDocument,但它不起作用。
答案 0 :(得分:0)
因此,如果我理解正确,您想要下载Feed,然后将项目放在List,数组或similair而不是列表框中?然后你可以简单地添加一行:
var feedItems = new List<SyndicationItem>(feed.Items);
我也觉得你想在一个函数中使用它,然后你可以使用Tasks来这样做:
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关键字,您可以在documentation中详细了解这些关键字。