Yas*_*hVj 2 c# rss foreach visual-studio-2012
我使用以下代码:
private string covertRss(string url)
{
var s = RssReader.Read(url);
StringBuilder sb = new StringBuilder();
foreach (RssNews rs in s) //ERROR LINE
{
sb.AppendLine(rs.Title);
sb.AppendLine(rs.PublicationDate);
sb.AppendLine(rs.Description);
}
return sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
错误1 foreach语句无法对类型为"System.Threading.Tasks.Task(System.Collections.Generic.List(Cricket.MainPage.RssNews))"的变量进行操作,因为'System.Threading.Tasks.Task(System.Collections.Generic) .List(Cricket.MainPage.RssNews))'不包含'GetEnumerator'的公共定义
RssNews课程是:
public class RssNews
{
public string Title;
public string PublicationDate;
public string Description;
}
Run Code Online (Sandbox Code Playgroud)
我应该添加什么代码,以便删除错误并且代码的目的不会被编译?提前致谢!
RssReader.Read()的代码
public class RssReader
{
public static async System.Threading.Tasks.Task<List<RssNews>> Read(string url)
{
HttpClient httpClient = new HttpClient();
string result = await httpClient.GetStringAsync(url);
XDocument document = XDocument.Parse(result);
return (from descendant in document.Descendants("item")
select new RssNews()
{
Description = descendant.Element("description").Value,
Title = descendant.Element("title").Value,
PublicationDate = descendant.Element("pubDate").Value
}).ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
你需要使用await:
foreach (RssNews rs in await s)
Run Code Online (Sandbox Code Playgroud)
要么:
var s = await RssReader.Read(url);
Run Code Online (Sandbox Code Playgroud)
千万不能使用Result; 如果你这样做,你很容易造成我在博客上描述的僵局.
作为旁注,我建议您阅读并遵循基于任务的异步模式文档中的指南.如果你这样做,你会发现你的方法Read应该被命名ReadAsync,这为你的调用代码提供了一个需要使用的强大提示await:
var s = await RssReader.ReadAsync(url);
Run Code Online (Sandbox Code Playgroud)