【问题标题】:Making an method execute on interval in Winforms in C#在 C# 中的 Winforms 中按间隔执行方法
【发布时间】:2011-04-09 09:44:13
【问题描述】:

我正在制作一个 RSS 阅读器,我希望它能够在给定的时间间隔内更新。 我对使用 Winforms Timer 组件不感兴趣。 我更多的是考虑使用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 timer


    【解决方案1】:

    【讨论】:

    • 如果您阅读我帖子的第一行,您会发现这不是我想要做的。
    【解决方案2】:

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

    例如

    你会有一个成员变量来判断进程是否正在运行以及时间间隔

    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')

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

    【讨论】:

    • 它可以工作,但与预期不符,我的整个程序在线程处于睡眠状态时冻结,这不是我想做的事情
    • 您的整个程序都冻结了?它不应该那样做。您在其他任何地方使用过 Thread.CurrentThread.Sleep 吗?唯一应该休眠的线程是您开始处理的线程
    【解决方案3】:

    这些东西我喜欢Reactive Extensions

    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 块,而不是通过控制台按键停止。

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

    【讨论】:

      猜你喜欢
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      相关资源
      最近更新 更多