Search code examples
c#multithreadingtimerbackgroundworkerintervals

Changing Timer Interval in Backgroundworker DoWork Disables the Timer [C#]


I have the problem with changing the timer Interval in backgroundworker's DoWork event. While changing the Interval by clicking the Button, Timer stops and doesn't start again.

Does anyone know how to solve this problem?

Simple code:

    public Form1()
    {
        InitializeComponent();
        timerTest.Tick += new EventHandler(timerTest_Tick);
        timerTest.Interval = 1000;
        timerTest.Start();
    }

    private void buttonTest_Click(object sender, EventArgs e)
    {
        push = true;
    }

    private void timerTest_Tick(object sender, EventArgs e)
    {
        ticks++;
        labelTest.Text = ticks.ToString();
        if(running == false)
        {
            running = true;
            backgroundWorkerTest.RunWorkerAsync();
        }
    }

    public void activate()
    {
        timerTest.Stop();
        timerTest.Interval = 4000;
        timerTest.Start();
    }

    private void DoWork(object sender, DoWorkEventArgs e)
    {
        while(running)
        {
           if(push == true)
           {
               activate();  
           }
        }
    }

    private void Completed(object sender, RunWorkerCompletedEventArgs e)
    {
        running = false;
    }
}

}


Solution

  • It took me a while, but I found out what was wrong. I'll post you a working code, just in case someone will have the same problem.

    public partial class Form1 : Form { public int ticks = 0; public bool running = false; public bool push = false;

        public Form1()
        {
            InitializeComponent();
            timerTest.Tick += new EventHandler(timerTest_Tick);
            timerTest.Interval = 1000;
            timerTest.Start();
        }
    
        private void buttonTest_Click(object sender, EventArgs e)
        {
            push = true;
        }
    
        private void timerTest_Tick(object sender, EventArgs e)
        {
            ticks++;
            labelTest.Text = ticks.ToString();
            if(running == false)
            {
                running = true;
                backgroundWorkerTest.RunWorkerAsync();
            }
        }
    
        public void activate()
        {
            ZmienIntervalNaAwaryjny = true;
        }
        public bool ZmienIntervalNaAwaryjny = false;
        private void DoWork(object sender, DoWorkEventArgs e)
        {
    
               if(push == true)
               {
                   activate();
               }
        }
    
        private void Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            if(ZmienIntervalNaAwaryjny == true)
            {
                timerTest.Stop();
                timerTest.Interval = 12000;
                timerTest.Start();
            }
            ZmienIntervalNaAwaryjny = false;
            running = false;
        }
    }