我遇到问题,我在button_click方法中使用backgroundWorker1.RunWorkerAsync()
,并且还使用backgroundWorker1_DoWork()
,backgroundWorker1_ProgressChanged()
事件,所有事件都在触发,但进度条没有刷新。这是我的代码:
private void btnMove_Click(object sender, EventArgs e)
{
try
{
backgroundWorker1.RunWorkerAsync();
for (int i = 0; i < gdFiles.Rows.Count - 1; i++)
{
// my process
}
catch (Exception ex)
{
}
}
}
事件是
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
backgroundWorker1.ReportProgress(i);
Thread.Sleep(100);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
progressBar1.Refresh();
}
任何人都可以帮忙吗.....
答案 0 :(得分:0)
检查backgroundWorker1.WorkerReportsProgress
的值,应将其设置为true。 Bellow工作和测试的例子:
public partial class Form1 : Form
{
private BackgroundWorker bw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
bw.ReportProgress(i);
Thread.Sleep(100);
}
}
private void button1_Click(object sender, EventArgs e)
{
bw.RunWorkerAsync();
}
}
答案 1 :(得分:0)
我试图复制你的问题,但我的工作正常。确保backgroundWorker1.ReposrtsProgress设置为 True 。请参阅以下代码:
'private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
backgroundWorker1.ReportProgress(i);
Thread.Sleep(100);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
progressBar1.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}`
另外,我认为你的“过程”应该在DoWork中。
答案 2 :(得分:0)
您不应该将文件移动逻辑移动到DoWork部分吗? BackgroundWorker的想法是从UI线程中删除繁重的东西。