Search code examples
c#winformstimer

How to add elapsed timer (min) to GUI , during progress bar running


I want to add elapsed time (minutes) to an GUI and do something else in parallel.

Everything I try does not succeed, it sticks in my gui. I add example:

namespace Backgrondworker
{
    public partial class Form1 : Form
    {
        int aa = 0;

        public Form1()
        {
            InitializeComponent();         
        }

        private void button1_Click(object sender, EventArgs e)
        {
            progressBar1.Value = 0;
            progressBar1.Maximum = 10;
            backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {          
            for(int i =1;i<=10;i++)
            {
                Thread.Sleep(1000);
                backgroundWorker1.ReportProgress(0);            
            }          
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value += 1;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("completed");

        }
    }
}

Solution

  • You should do the following

    1. Create a Timer
    2. Start the timer when you start the progress bar
    3. In the timer, tick use the timespan class and Elapsed property to get the elapsed minutes and show them in a label.
    4. Stop the Timer when the progressbar is at maxsize.