Reputation: 9
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
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
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
Reputation: 362
You should do the following
Upvotes: 1