Kobi Edri
Kobi Edri

Reputation: 9

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");

        }
    }
}

Upvotes: 0

Views: 545

Answers (3)

Kobi Edri
Kobi Edri

Reputation: 9

I explain: public partial class Form1 : Form {

    public Form1()
    {
        InitializeComponent();         
    }

    private void button1_Click(object sender, EventArgs e)
    {

        Task.Run(() =>
        {
            for (int i = 1; i <= 10; i++)
            {
                Thread.Sleep(1000);
                label2.Text = i.ToString();
            }
        });

        Task.Run(() =>
        {
            for (int i = 1; i <= 10; i++)
            {
                Thread.Sleep(1000);
                label3.Text = i.ToString();
            }
        });
    } 
}

got : System.InvalidOperationException: 'Cross-thread operation not valid: Control 'label3' accessed from a thread other than the thread it was created on.'

Upvotes: 0

Eliahu Aaron
Eliahu Aaron

Reputation: 4542

You put 0 in ReportProgress:

backgroundWorker1.ReportProgress(0);

Change this to:

int percent = (int)Math.Round((i * 100.0) / 10);
backgroundWorker1.ReportProgress(percent);

Dividing by 10 gives you the fraction of work done (you count 10 times in the loop) and multiplying by 100 is for getting the percent.

Upvotes: 0

Maniac
Maniac

Reputation: 362

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.

Upvotes: 1

Related Questions