backgroundWorker_ProgressChanged not working?
本文关键字:working not ProgressChanged backgroundWorker | 更新日期: 2023-09-27 18:21:29
后台工作程序出现问题
private void backgroundPBar_ProgressChanged(object sender, ProgressChangedEventArgs e)
当backgroundPBar.ReportProgress(value)
这是代码:
private void backgroundPBar_DoWork(object sender, DoWorkEventArgs e) {
while (fileTransfer.busy) {
if (fileTransfer.sum > 0) {
int value = Convert.ToInt32((fileTransfer.sum * 100) / fileTransfer.fileSize);
backgroundPBar.ReportProgress(value);
Console.WriteLine(value);
}
}
}
private void backgroundPBar_ProgressChanged(object sender, ProgressChangedEventArgs e) {
progressBarFile.Value = e.ProgressPercentage;
this.Text = e.ProgressPercentage.ToString() + "%";
}
我该怎么修?
确保已连接进度事件:
backgroundPBar.ProgressChanged += backgroundPBar_ProgressChanged
从你的描述来看,似乎不是。这里的假设是fileTransfer.busy
是真的,并且fileTransfer.sum > 0
也是真的。
此外,请确保您拥有后台工作程序集的属性:
backgroundPBar.WorkerReportsProgress = true;
(正如我所看到的"面具"提到的)。
ReportProgress()
方法,必须将WorkerReportsProgress
设置为true
。
在调用ReportProgress方法时,我遇到了让ProgressChanged事件立即激发的问题。因为它们是独立的线程,所以我不得不求助于线程同步。我使用了两个WaitHandles和SignalAndWait方法来同步这两个线程。我有点违背了后台工作程序的目的,但如果我真的想让UI线程按时做一些事情,那就必须让后台工作程序等到UI线程收到消息并执行工作。
Private ReportProgressWaitEvent As New AutoResetEvent(False)
Private ReportProgressReadyWaitEvent As New ManualResetEvent(False)
Private Sub ReportProgress(backgroundWorkerProgressEvents As BackgroundWorkerProgressEventsEnum, userState As Object)
ReportProgressReadyWaitEvent.Reset()
_backgroundWorker.ReportProgress(backgroundWorkerProgressEvents, userState)
WaitHandle.SignalAndWait(ReportProgressReadyWaitEvent, ReportProgressWaitEvent)
End Sub
Private Sub _backgroundWorker_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles _backgroundWorker.ProgressChanged
... do work ...
ReportProgressReadyWaitEvent.WaitOne()
ReportProgressWaitEvent.Set()
End Sub
下面是如何使用ProgressBar的backgroundworker的教程
您应该首先调用(RunWorkerSync),然后后台PBar_DoWork将开始执行其代码。
backgroundPBar.RunWorkerAsync();