Search code examples
c#.nettimertry-catch

Stop Timer Within Try Catch


Not sure why this isn't working. I have a timer defined, which runs a method every 2 seconds. Within that method I have a try/catch. Try to execute this code, catch should disable the timer and then display a message box. For some reason my message box displays over and over every 2 seconds. Why won't my timer disable?

    Timer timer1 = new Timer();

    public MainForm()
    {
        timer1.Interval = 2000;
        timer1.Tick += new EventHandler(OnTimer);
        timer1.Enabled = true;
        //More code
    }

    private void OnTimer(object sender, EventArgs e)
    {
        try
        {
            //Code
        }

        catch (Exception)
        {
            MessageBox.Show("Message");
            timer1.Enabled = false;
            this.Dispose();
        }
    }

Thanks. -Jason


Solution

  • I'm guessing MessageBox.Show("Message") is blocking execution of timer1.Enabled = false; because it is a modal dialog. Try disabling the timer so it won't keep on firing the OnTimer callback first, before displaying the modal dialog:

    private void OnTimer(object sender, EventArgs e)
    {
        try
        {
            // Code
        }
    
        catch (Exception)
        {
            timer1.Enabled = false;
            MessageBox.Show("Message");
            this.Dispose();
        }
    }