Can somebody explain to me what this does?

71 views Asked by At

So, I'm quite new to C# programming, and I had a friend help me out. He made this code:

    private void Form1_Shown(object sender, EventArgs e)
    {
        System.Timers.Timer t = new System.Timers.Timer(50);

        t.Elapsed += t_Elapsed;

        t.Start();
    }

    void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        ((System.Timers.Timer)sender).Stop();

        DisplayOrder();
    }

Which is used to pause the program for a short duration of time, before it "resetting".

Right above the evnthandler itself, it is used like this in a "label_Click" eventhandler:

            System.Timers.Timer t = new System.Timers.Timer(500);

            t.Elapsed += t_Elapsed;

            t.Start();
2

There are 2 answers

0
horHAY On
private void Form1_Shown(object sender, EventArgs e) // Shown is an event that occurs when the form is first shown
{
    System.Timers.Timer t = new System.Timers.Timer(50); // This creates a new timer with an interval of 50 ms

    t.Elapsed += t_Elapsed; // The timer is assigned event for when the interval has elapsed - when 
                            // started the, the elapsed event will occur when the given interval 
                            // has elapsed (in this case 50ms)

    t.Start(); // Starts the timer
}
0
dcastro On

That creates a timer t which will call the handler (t_Elapsed) every 50ms. The handler will then disable the timer and call DisplayOrder - which means the handler will be called just once.

Basically, it waits for 50ms before calling DisplayOrder. You might as well have done this instead:

private async void Form1_Shown(object sender, EventArgs e)
{
    await Task.Delay(50);
    DisplayOrder();
}