1

I want to make a RSS reader which makes it possible to get multiple news feeds at the same time, without my application "freezing" while getting the feed. To do this, I want some of the code to run in a seperate thread. I have tried some different things, to make it run in a seperate thread, but I keep getting exceptions. My code looks like this atm:

namespace NewsReader
{
    public partial class Form1 : Form
    {
        XmlTextReader rssReader;

        XmlDocument rssDoc;

        XmlNode nodeRss;

        XmlNode nodeChannel;

        XmlNode nodeItem;

        ListViewItem rowNews;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnRead_Click(object sender, EventArgs e)
        {

            //Creates a XmlTextReader which reads from the url entered in input field
            rssReader = new XmlTextReader(txtUrl.Text);

            //Creates an xml doc to save the content of the entered path
            rssDoc = new XmlDocument();

            //Loads the xml content from the reader into a XmlDocument
            rssDoc.Load(rssReader);


            //Make a loop to search for the <rss> tag
            for (int i = 0; i < rssDoc.ChildNodes.Count; i++)
            {
                //If the childenode is the rss tag
                if (rssDoc.ChildNodes[i].Name == "rss")
                {
                    //the <rss> tag is found, and we know where it is
                    nodeRss = rssDoc.ChildNodes[i];
                }
            }

            //Make a loop to search for the <channel> tag
            for (int i = 0; i < nodeRss.ChildNodes.Count; i++)
            {
                //If the childnode is the channel tag
                if (nodeRss.ChildNodes[i].Name == "channel")
                {
                    //The channel tag is found and we know where it is
                    nodeChannel = nodeRss.ChildNodes[i];
                }
            }

            //Make a loop to search for the <item> tag
            for (int i = 0; i < nodeChannel.ChildNodes.Count; i++)
            {
                //If the childnode is the item tag
                if (nodeChannel.ChildNodes[i].Name == "item")
                {
                    //the item tag is found, and we know where it is
                    nodeItem = nodeChannel.ChildNodes[i];

                    //Creates a new row in the LstView which contains information from inside the nodes
                    rowNews = new ListViewItem();
                    rowNews.Text = nodeItem["title"].InnerText;
                    rowNews.SubItems.Add(nodeItem["link"].InnerText);
                    lstView.Items.Add(rowNews);

                }
            }

        }
    }

}

Does anyone have some examples of how to handle this problem? Code examples with my code is very appreciated :)

Thanks in advance.

3 Answers 3

2

You may checkout the BackgroundWorker class. And here's an example:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.XPath;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync(txtUrl.Text);
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        var rssDoc = XDocument.Load((string)e.Argument);
        var items = new List<ListViewItem>();
        foreach (var item in rssDoc.XPathSelectElements("//item"))
        {
            var listItem = new ListViewItem();
            listItem.Text = item.Element("title").Value;
            listItem.SubItems.Add(item.Element("link").Value);
            items.Add(listItem);
        }
        e.Result = items.ToArray();
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        lstView.Items.AddRange((ListViewItem[])e.Result);
    }
}
0

If you're using .NET 3.5 or later you can use the SyndicationFeed type to make parsing the RSS feed easier.

I'm adapting Darin Dimitrov's code example here:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.ServiceModel.Syndication;
using System.Xml.Linq;
using System.Xml.XPath;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync(txtUrl.Text);
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        var reader = new XmlTextReader((string)e.Argument);
        var feed = SyndicationFeed.Load(reader);
        var items = new List<ListViewItem>();
        foreach (var item in feed.Items)
        {
            var listItem = new ListViewItem();
            listItem.Text = item.Title;
            foreach (var link in item.Links)
            {
                listItem.SubItems.Add(link.Uri.AbsoluteUri);
            }
            items.Add(listItem);
        }
        e.Result = items.ToArray();
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        lstView.Items.AddRange((ListViewItem[])e.Result);
    }
}
0

If you are using .net 4.0 you can use the Task system for an even easier approach, and possibly better performance.

  foreach (var item in rssDoc.XPathSelectElements("//item"))
  {
    Task fetch = new Task(() =>
    {
     // Go to server and get data....
     // Add Data to UI...
    });

    fetch.Start();
  }

The main benefit here is the Task system will decide how and when to run each fetch operation. In theory each operation will run in its own thread, so one or more at a time will be active instead of just one that you would see in a normal loop. The system is nice enough to do some load balancing for you too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.