Running a method in BackGroundWorker and Showing P

2019-01-07 22:09发布

What I want is when some method is doing some task UI keeps itself active and I want to show the progress of the work in a progress-bar.

I have a method, a BackGroundWorker and a Progressbar. I want to call the method when BackGroundWorker starts running and show the progress. The method contains a loop. So, it can report the progress.

So, what can be done?

private void Form1_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'dataSet1.TBLMARKET' table. You can move, or remove it, as needed.
    myBGWorker.WorkerReportsProgress = true;
}

private void myBGWorker_DoWork(object sender, DoWorkEventArgs e)
{
    parseFiles();
}

private void myBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    myProgressBar.Value = e.ProgressPercentage;
}

private void myBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    MessageBox.Show("Done");
}

private void parseButton_Click(object sender, EventArgs e)
{
    myBGWorker.RunWorkerAsync();
}

public void parseFiles()
{
  for()
  {
     //parsing
     myBGWorker.ReportProgress(...);
  }
}

But it's not working. The Progressbar is not updating. Only a small progress is showing after the MessageBox "Done".

3条回答
SAY GOODBYE
2楼-- · 2019-01-07 22:20

I am sorry about the question. Actually the code works fine. It was not showing the Progressbar as the argument in myBGWorker.ReportProgress() was fraction and not percentage. So, it was not showing it. Sorry for the inconvenience.

Moderator may delete this thread. Otherwise it can be a tutorial for others.

查看更多
我命由我不由天
3楼-- · 2019-01-07 22:22

Instead of using one ParseFiles method (which should depend on myBGWorker) use loop and method which parse one file. Report progress percentage in that loop:

private void parseButton_Click(object sender, EventArgs e)
{
    parseButton.Enabled = false;
    myBGWorker.RunWorkerAsync();
}

private void myBGWorker_DoWork(object sender, DoWorkEventArgs e)
{
   for(int i = 0; i < filesCount; i++)
   {  
       ParseSingleFile(); // pass filename here
       int percentage = (i + 1) * 100 / filesCount;
       myBGWorker.ReportProgress(percentage);
   }
}

void myBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    myProgressBar.Value = e.ProgressPercentage;
}

void myBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    parseButton.Enabled = true;
    MessageBox.Show("Done");
}
查看更多
Evening l夕情丶
4楼-- · 2019-01-07 22:22

To. soham.m17 using with sender argument

private void myBGWorker_DoWork(object sender, DoWorkEventArgs e)
{
   var worker = sender as BackgroundWorker;
   for(int i = 0; i < filesCount; i++)
   {  
       ParseSingleFile(); // pass filename here
       int percentage = (i + 1) * 100 / filesCount;
       worker.ReportProgress(percentage);  // use not myBGWorker but worker from sender
   }
}
查看更多
登录 后发表回答