c# winform background worker and progress bar

血红的双手。 提交于 2019-11-28 11:45:36

问题


I am trying to get the progress bar to increment using a BG Worker. I am currently using 2 BG workers, one to add data into a DB and one for the progress bar. The DB upload is working fine, yet the progress bar is not.

Code:

BackgroundWorker bg2 = new BackgroundWorker();
bg2.DoWork +=new DoWorkEventHandler(bg2_DoWork);
bg2.RunWorkerAsync();

void bg2_DoWork(object sender, DoWorkEventArgs e)
    {

        while (bg1.IsBusy)
            DrawWellPlate.pbar.Increment(1)
    }

bg1 that it refers to is the database upload thread and pbar is clearly the progress bar.

Thanks.


回答1:


You should do something like this where totalProgress will be shown in progressBar, doWork is executed not in UI thread, that is the purpose of BackgroundWorker

BackgroundWorker bg2 = new BackgroundWorker();
bg2.DoWork +=new DoWorkEventHandler(bg2_DoWork);
.ProgressChanged += new ProgressChangedEventHandler(bg2_ProgressChanged)
bg2.RunWorkerAsync();

void bg2_DoWork(object sender, DoWorkEventArgs e)
    {

        while (bg1.IsBusy)
            worker.ReportProgress(totalProgress);
    }
private void bg2_ProgressChanged(object sender,
            ProgressChangedEventArgs e)
        {
            DrawWellPlate.pbar.Value = e.ProgressPercentage;
        }

see this for more details




回答2:


The issue is that bg1 will always report that it is busy while it runs its DoWork method.

You should use just ONE background worker and in its do work method something like this (pseudo code):

void bg1_DoWork(object sender, DoWorkEventArgs e)
{
    while(got_stuff_to_add_to_the_database)
    {
       //do *some* of the work
       AddABit()

       //Update the progress - 5% at a time?
       totalProgress += 5

       //update the progress bar
       ReportProgress(totalProgress)

       if(finished)
       {
           got_stuff_to_add_to_the_database = false;
       }
    }
}


来源:https://stackoverflow.com/questions/4604558/c-sharp-winform-background-worker-and-progress-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!