Search code examples
c#loopslagmilliseconds

Loop every 500 milliseconds without lag


How can I do this in a WinForms app? I've tried it with a System.Windows.Forms.Timer, but when i minimize the application, I can't maximize it again. It lags up the app. I'm using the .Interval property as 500.

EDIT: Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Timer Loop = new System.Windows.Forms.Timer();
            Loop.Interval = 500;
            Loop.Tick += new EventHandler(UpdateUI);
            Loop.Start();
        }

        void UpdateUI(object sender, EventArgs e)
        {
            //ADD TO LIST ON USER INTERFACE
        }
    }
}

Solution

  • The Timer class specifies Interval as milliseconds. So your value of 500 indicates an interval of half a second. Specify 50 instead.

    Also, you are not guaranteed to have the timer fire exactly each 50 milliseconds. Only somewhere around 50 milliseconds.

    You should keep a reference to your timer object.

    public partial class Form1 : Form
    {
        Timer loop;
    
        public Form1()
        {
            InitializeComponent();
            this.loop = new System.Windows.Forms.Timer();
            loop.Interval = 50;
            loop.Tick += new EventHandler(UpdateUI);
            loop.Start();
        }
    
        void UpdateUI(object sender, EventArgs e)
        {
            //ADD TO LIST ON USER INTERFACE
        }
    }