Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# timer issue

Tags:

c#

.net

timer

Hello I'm currently having an issue with a timer in a program I'm developing. The timer runs and calls methods which retrieve Windows Management Information from remote PC's after a set period of time and repeat this.

The first time the timer calls these all is well, however the second time, after the timer has completed its task, it loops through itself again and the third time it runs it does it 3 times etc. The for loop in the code below works fine its the timer itself.

So any help would be appareciated and if you require any further details please let me know.

Below is my code:

private void tmrStore_Tick(object sender, EventArgs e)
    {
        string ipAdd;
        ipAdd = "127.0.0.1";
        List<TblServer> Server;

        WMIInfo localDB = new WMIInfo("Data Source=|DataDirectory|\\WMIInfo.sdf");

        Server = localDB.TblServer.ToList();

        if (Server.Count == 0)
        {

        }
        else
        {
            for (int counter = 0; counter < Server.Count; counter++)
            {
                CPUStore cpu = new CPUStore();
                cpu.Store(Server[counter].IpAdd);

                HDDStore hdd = new HDDStore();
                hdd.Store(Server[counter].IpAdd);

                MemStore mem = new MemStore();
                mem.Store(Server[counter].IpAdd);

                //delete items over 24 hours old 
            }
        }
like image 894
manemawanna Avatar asked Jul 22 '26 07:07

manemawanna


1 Answers

Try disabling the timer before performing the management task, then reenabling:

tmrStore.Enabled = false;
try{
    // do stuff
}finally{
    tmrStore.Enabled = true;
}

The cause of the problem is probably that the body of your timer handler takes longer to execute than your Timer.Ticks value, so your timer events start to stack on top of each other.

You might also consider putting this code in a thread instead of a timer, so that it's independent of your user interface.

like image 94
Dmitry Brant Avatar answered Jul 23 '26 21:07

Dmitry Brant