gpt4 book ai didi

c# - Backgroundworker 不会报告进度

转载 作者:IT王子 更新时间:2023-10-29 04:46:07 26 4
gpt4 key购买 nike

我有一个后台工作人员在运行一个长时间的数据库任务。我想在任务运行时显示进度条。不知何故,后台工作人员不会报告任务的进度。

这是我的:

BackgroundWorker _bgwLoadClients;

_bgwLoadClients = new BackgroundWorker();
_bgwLoadClients.WorkerReportsProgress = true;
_bgwLoadClients.DoWork += new DoWorkEventHandler(_bgwLoadClients_DoWork);
_bgwLoadClients.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_bgwLoadClients_RunWorkerCompleted);
_bgwLoadClients.ProgressChanged += new ProgressChangedEventHandler(_bgwLoadClients_ProgressChanged);
_bgwLoadClients.RunWorkerAsync(parms);

private void _bgwLoadClients_DoWork(object sender, DoWorkEventArgs e)
{
DataTable dt = getdate();
e.Result = dt;
}

void _bgwLoadClients_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}

我在 WPF 中这样做,但我想这不会有什么不同。

提前致谢

最佳答案

您需要将 DoWork 方法分解为可报告的进度,然后调用 ReportProgress。

以下面的例子为例:

private void Something_DoWork(object sender, DoWorkEventArgs e) 
{
// If possible, establish how much there is to do
int totalSteps = EstablishWorkload();

for ( int i=0; i<totalSteps; i++)
{
// Do something...

// Report progress, hint: sender is your worker
(sender as BackgroundWorker).ReportProgress((int)(100/totalSteps)*i, null);
}

}

如果您的工作无法预先确定,请尝试添加您自己的百分比:

private void Something_DoWork(object sender, DoWorkEventArgs e) 
{
// some work

(sender as BackgroundWorker).ReportProgress(25, null);

// some work

(sender as BackgroundWorker).ReportProgress(50, null);

// some work

(sender as BackgroundWorker).ReportProgress(60, null);

// some work

(sender as BackgroundWorker).ReportProgress(99, null);
}

关于c# - Backgroundworker 不会报告进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/854548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com