Florin C.
Florin C.

Reputation: 366

Implement multiple timers in C#

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!

Upvotes: 0

Views: 3412

Answers (2)

StaWho
StaWho

Reputation: 2498

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

Upvotes: 4

aiodintsov
aiodintsov

Reputation: 2605

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

Upvotes: 1

Related Questions