RSS阅读器多线程C#

发布于 2024-10-30 21:32:37 字数 2635 浏览 1 评论 0原文

我想制作一个 RSS 阅读器,它可以同时获取多个新闻提要,而我的应用程序在获取提要时不会“冻结”。为此,我希望一些代码在单独的线程中运行。我尝试了一些不同的方法,使其在单独的线程中运行,但我不断收到异常。我的代码看起来像这样 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);

                }
            }

        }
    }

}

有谁有一些如何处理这个问题的例子吗?非常感谢带有我的代码的代码示例:)

提前致谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

情独悲 2024-11-06 21:32:37

您可以查看 BackgroundWorker 类。这是一个例子:

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);
    }
}

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);
    }
}
甜心 2024-11-06 21:32:37

如果您使用的是 .NET 3.5 或更高版本,则可以使用 SyndicateFeed< /code>类型以使解析 RSS 提要更容易。

我在这里改编了 Darin Dimitrov 的代码示例:

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);
    }
}

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);
    }
}
情话已封尘 2024-11-06 21:32:37

如果您使用 .net 4.0,您可以使用任务系统获得更简单的方法,并且可能获得更好的性能。

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

    fetch.Start();
  }

这里的主要好处是任务系统将决定如何以及何时运行每个获取操作。理论上,每个操作都将在其自己的线程中运行,因此一次一个或多个操作将处于活动状态,而不是您在正常循环中看到的仅一个操作。该系统也足够好,可以为您做一些负载平衡。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文