在c#的Winforms中间隔执行一个方法

本文关键字:一个 方法 执行 Winforms 中间 | 更新日期: 2023-09-27 17:49:38

我正在制作一个RSS阅读器,我希望它能够在给定的时间间隔内更新。我对使用Winforms计时器组件不感兴趣。我更想用System.Threading.Timer .

我想要间隔执行的方法是这样的:

public void getNews()
{
    for (int i2 = 0; i2 < urlList.Count; i2++)
    {
        //Creates a XmlTextReader which reads from the url entered in input field
        rssReader = new XmlTextReader(urlList[i2]);
        //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);
                if (this.lstView.InvokeRequired)
                {
                    AddItemCallback d = new AddItemCallback(getNews);
                    this.Invoke(d);
                    return;
                }
                lstView.Items.Add(rowNews);
            }
        }
    }
}

这是执行方法的按钮:

private void btnRead_Click(object sender, EventArgs e)
{
    lstView.Items.Clear();
    Thread myThread = new Thread(getNews);
    myThread.Start();
}

如何在特定的间隔上执行getNews()方法?示例与我的代码非常感谢。

在c#的Winforms中间隔执行一个方法

用户定时器控件并在Tick事件中编写代码…http://www.c-sharpcorner.com/UploadFile/mahesh/WorkingwithTimerControlinCSharp11302005054911AM/WorkingwithTimerControlinCSharp.aspx

我将启动一个新线程,并在它结束时为指定的间隔休眠。

例如

将有一个成员变量表示进程是否正在运行,以及间隔

private bool _isRunning = false;
private int _interval = 1000;
然后在start方法中创建一个新线程
public void Start()
{
  ThreadStart oThreadStart = new ThreadStart(DoWork);
  Thread t = new Thread(oThreadStart);
  _isRunning = true;
  t.Start();
}
public void Stop()
{
    _isRunning = false;
}
private void DoWork()
{
   while(_isRunning)
   {
     // do work
     Thread.Sleep(_interval);
   }
   Thread.CurrentThread.Join();
}

然后你把所有的处理都放在一个线程上,它在不使用的时候睡觉(例如等待下一个'tick')

同样,使用此方法可以防止在第一个tick事件完成处理之前触发第二个tick事件的可能性

我喜欢这些东西的响应式扩展。

var observable = Observable.Interval(TimeSpan.FromSeconds(2)); // Interval in seconds
var subscription = observable.Subscribe(_ => getNews());
// Or if it does not work then try this:
var subscription = observable.ObserveOnWindowsForms().Subscribe(_ => getNews());
using (subscription)
{
    Console.WriteLine("Press any key to stop...");
    Console.ReadKey();
}

你可以在subscription上调用.Dispose()并删除整个using块,而不是用控制台键停止。

要测试这种方法,请尝试将_ => getNews()替换为Console.WriteLine,然后您将看到它是如何工作的:)(这是一个来自http://rxwiki.wikidot.com/101samples的示例)