Implement multiple timers in C#

落爺英雄遲暮 提交于 2019-12-13 02:46:34

问题


I'm working on a windows forms app where I have several so called "services" that poll data from various services like Twitter, Facebook, Weather, Finance. Now each of my services has its individual polling interval setting so I was thinking I could implement a System.Windows.Forms.Timer for each of my services and set its Interval property accordingly so that each timer would fire an event at the preset interval that will cause the service to pull new data preferably async through a BackgroundWorker.

Is this the best way to do it? or will it slow down my app causing performance issues. Is there a better way of doing it?

Thanks!


回答1:


You can do it with one Timer, just needs smarter approach to interval:

public partial class Form1 : Form
{
    int facebookInterval = 5; //5 sec
    int twitterInterval = 7; //7 sec

    public Form1()
    {
        InitializeComponent();

        Timer t = new Timer();
        t.Interval = 1000; //1 sec
        t.Tick += new EventHandler(t_Tick);
        t.Start();
    }

    void t_Tick(object sender, EventArgs e)
    {
        facebookInterval--;
        twitterInterval--;

        if (facebookInterval == 0)
        {
            MessageBox.Show("Getting FB data");
            facebookInterval = 5; //reset to base value
        }

        if (twitterInterval == 0)
        {
            MessageBox.Show("Getting Twitter data");
            twitterInterval = 7; //reset to base value
        }
    }
}



回答2:


you do not really need BackgroundWorker, as WebClient class has Async methods.

so you may simply have one WebClient object for each of your "service" and use code like this:

facebookClient = new WebClient();
facebookClient.DownloadStringCompleted += FacebookDownloadComplete;
twitterClient = new WebClient();
twitterClient.DownloadStringCompleted += TwitterDownloadComplete;

private void FacebookDownloadComplete(Object sender, DownloadStringCompletedEventArgs e)
{
    if (!e.Cancelled && e.Error == null)
    {
        string str = (string)e.Result;
        DisplayFacebookContent(str);
    }
}
private void OnFacebookTimer(object sender, ElapsedEventArgs e)
{
     if( facebookClient.IsBusy) 
         facebookClient.CancelAsync(); // long time should have passed, better cancel
     facebookClient.DownloadStringAsync(facebookUri);
}


来源:https://stackoverflow.com/questions/12314673/implement-multiple-timers-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!