I am using the following code:
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();
}
I am getting an error:
Error 1 foreach statement cannot operate on variables of type 'System.Threading.Tasks.Task(System.Collections.Generic.List(Cricket.MainPage.RssNews))' because 'System.Threading.Tasks.Task(System.Collections.Generic.List(Cricket.MainPage.RssNews))' does not contain a public definition for 'GetEnumerator'
The RssNews class is:
public class RssNews
{
public string Title;
public string PublicationDate;
public string Description;
}
What code should i add so the error is removed and the purpose of the code is not compramised? Thanks in advance!
Code for 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();
}
}
You need to use await:
foreach (RssNews rs in await s)
or:
var s = await RssReader.Read(url);
Do not use Result; if you do, you can easily cause a deadlock that I describe on my blog.
As a side note, I recommend that you read and follow the guidelines in the Task-based Asynchronous Pattern documentation. If you do, you'll find that your method Read should be named ReadAsync, which gives your calling code a strong hint that it needs to use await:
var s = await RssReader.ReadAsync(url);
I think you're missing an await statement.
It appears s is of type Task<List<RssNews>>.
You either need this
var s = await RssReader.Read(url);
or
var s = RssReader.Read(url).Result;//this is blocking call
Of course when you use await you need to mark the method async as well.
Here is how you go
private async Task<string> covertRss(string url)
{
var s = await 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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With