问题
i'm trying to do the code here
http://www.dotnetperls.com/progressbar
Here is the code I have. I've drawn on a backgroundworker, and programmatically added a progress bar.
I've tried stepping over the code, and i've tried using messageboxes to see what is going on, and it looks like it is only executing one iteration of the for loop, which is for when i=0, and it seems it goes from that, to te done procedure, and the Progress procedure never gets invoked.
And the progress bar never changes value from 0.
When I want it to progress to 100.
I did try commenting out this line //Application.EnableVisualStyles();
in program.cs to remove a natural animation that the progerss bar has, but either way, commented or uncommented, jt's not even running every iteration of the for loop, it's quitting after i=0.. And there is no progress with the backgroundworker, or the progress bar.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace backgroundworker2
{
public partial class Form1 : Form
{
ProgressBar progressBar1 = new ProgressBar();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// progressBar1.BackColor = Color.Red;
this.Controls.Add(progressBar1);
//progressBar1.Value = 100;
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// textBox1.Text = "0";
for (int i = 0; i < 100; i++)
{
// MessageBox.Show("a"+i);
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("done");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// textBox1.Text = Convert.ToString( e.ProgressPercentage);
progressBar1.Value = e.ProgressPercentage;
// MessageBox.Show("asdf");
}
}
}
回答1:
In Form1_Load
you run the BackgroundWorker
but you haven't set it's WorkerReportsProgress
property to true
. The default is false
. So you need to add this line before you call the RunWorkerAsync()
method:
backgroundWorker1.WorkerReportsProgress = true;
来源:https://stackoverflow.com/questions/37625930/cannot-get-progressbar-animation-with-code-progresschanged-not-called