繁体   English   中英

C#WinForm背景工作者和进度条

[英]c# winform background worker and progress bar

我正在尝试使用BG Worker来增加进度条。 我目前正在使用2个BG工人,一个将数据添加到数据库中,一个用于进度条。 数据库上传工作正常,但进度条却没有。

码:

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是数据库上传线程,而pbar显然是进度条。

谢谢。

您应该执行类似的操作,其中totalProgress将显示在progressBar中,doWork不是在UI线程中执行的,这是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;
        }

看到这个更多的细节

问题在于,bg1在运行其DoWork方法时将始终报告其繁忙。

您应该只使用一个后台工作人员,并且在其do方法中使用类似以下内容(伪代码)的方法:

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;
       }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM