0

I have a button to start the Timer1, the Timer1 will print the current execution time every 100ms, but when I do something calculation, the timer1_Tick() will be paused until finished that calculation, I think the calculation bother the Timer1 so that timer1_Tick() is dropped(or blocked this thread).

In fact, the calculation is very complex, maybe take 40 seconds, I just need to show the execution time every 100ms to tell user how close to the end of this function, would you please tell me how to do this work??

    double a = 0;
    public Form1()
    {
        InitializeComponent();
        timer1.Interval = 100;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {

        a += 0.1;
        label1.Text = a.ToString();
    }

    private void UserStartTimer_Click(object sender, EventArgs e)
    {
        a = 0.0;
        timer1.Enabled = true;

    }

    private void UserCalcSomething_Click(object sender, EventArgs e)
    {
        double s = 0;
        for (int i = 0; i < 100000; i++)
        {
            for (int j = 0; j < 10000; j++)
            {
                s = i + j;
            }
        }
    }

    private void UserStopTimer_Click(object sender, EventArgs e)
    {
        timer1.Enabled = false;
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
莊子子
  • 9
  • 1
  • Possible duplicate of [WinForm Application UI Hangs during Long-Running Operation](https://stackoverflow.com/questions/1216791/winform-application-ui-hangs-during-long-running-operation) – NineBerry Sep 09 '18 at 03:19
  • Thx for your reply. but in fact, the Long-Running Operation in my case contain lots of "thread.sleep(random)" and "update label/button/chart", not just loop of loop, so even I add Application.DoEvent(), the priority of "thread.sleep(random)" is still higher than Timer-object – 莊子子 Sep 09 '18 at 04:14
  • 1
    There is no real-time on a non real-time operating system. The timers are **not** accurate and the meaning of an interval set to 100 is *Well, after 100 milliseconds **or more** the Tick event will be signaled* – Sir Rufo Sep 09 '18 at 05:49

1 Answers1

1

Just execute the calculation in another thread or task:

private void UserCalcSomething_Click(object sender, EventArgs e)
{
    Task.Factory.StartNew(() => {
       double s = 0;
       for (int i = 0; i < 100000; i++)
       {
           for (int j = 0; j < 10000; j++)
           {
               s = i + j;
           }
       }
    }
}
Ali Doustkani
  • 728
  • 7
  • 14