Timer-related void call bugs out entire program

56 views Asked by At

Okay so here is the important bit of the code:

public bool open = false;

//CODE FOR CALLING VOID "EverySecond"
var DT = new System.Timers.Timer();     //Yes i am using System.Timers
DT.Elapsed += new ElapsedEventHandler(EverySecond);
DT.Interval = 1000;
/*
    SOME CODE CHANGING SOME UNIMPORTANT TEXTBOXES
*/
DT.Start();

private void EverySecond(object source, ElapsedEventArgs e)
{
    if (pb1.Value < 100)
        pb1.Value += 1;
    sl -= 1;
    tbTime.Text = "Estimated " + sl.ToString() + " seconds left";
    if (pb1.Value >= 100)
        pb1.Value = 100;
    if (pb1.Value == 100 && open == false)
    {
        Form frm6 = new frm6();
        frm6.Show();
        this.Close();
    }
}

So basically everytime i run this all the code runs fine, but then i come to this piece of code (if (pb1.Value == 100 && open == false)) and the entire program freezes and outputs 1 Form a second (which is logical due to the current configuration of the script) BUT i have tried it a million different ways and it does somewhat the same, it just shows me the hourglass cursor and all the buttons and textboxes are misplaced and the progressbar disappears, and it's just a mess.

1

There are 1 answers

0
Brooke Aniston On BEST ANSWER

I solved it, you need to use a regular Forms.Timer instead, and replace "Timer.Elapsed" with "Timer.Tick" and removed "Elapsed" from "ElapsedEventHandler" and "ElapsedEventArgs" Like this:

public bool open = false;

//CODE FOR CALLING VOID "EverySecond"
Timer DT = new Timer();
DT.Tick += new EventHandler(EverySecond);
DT.Interval = 1000;
/*
    SOME CODE CHANGING SOME UNIMPORTANT TEXTBOXES
*/
DT.Start();

private void EverySecond(object source, EventArgs e)
{
    if (pb1.Value < 100)
        pb1.Value += 1;
    sl -= 1;
    tbTime.Text = "Estimated " + sl.ToString() + " seconds left";
    if (pb1.Value >= 100)
        pb1.Value = 100;
    if (pb1.Value == 100 && open == false)
    {
        Form frm6 = new frm6();
        frm6.Show();
        this.Close();
    }
}