我正在使用Backgroundworker在处理过程中显示加载程序。但是加载程序(Progressbar)不会更新,只会在完成后更新。每当调用worker ProgressChanged事件时,它都不会更新进度条标签的值。这可能是由于异步行为导致的ProgressChanged事件。我是线程新手,请帮助。
void worker_DoWork(object sender, DoWorkEventArgs e)
{
bool isCompletedSuccessfully = true;
FileSQLHelper objSqlHelper = new FileSQLHelper();
PGPUtil utilityObj = new PGPUtil();
#region Outcoming
try
{
objSqlHelper.OpenConnection();
List<File> fileList = objSqlHelper.GetFilesList();
double totalRecord = fileList.Count();
int counter = 1;
foreach (var Fileitem in fileList)
{
double progressStatus = (counter / totalRecord) * 100;
(sender as BackgroundWorker).ReportProgress((int)progressStatus);
// my code here
counter++;
}
}
catch (Exception ex)
{
isCompletedSuccessfully = false;
MessageBox.Show(ex.Message, "Error");
}
finally
{
if (isCompletedSuccessfully == true)
{
MessageBox.Show("Completed Successfully!", "Information");
}
else if (isCompletedSuccessfully == false)
{
// MessageBox.Show("Completed Unsuccessfully!", "Information");
}
}
#endregion
}
private void Button_Click(object sender, RoutedEventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.ProgressChanged += worker_ProgressChanged;
worker.RunWorkerAsync();
// worker.RunWorkerAsync();
}
报告进度时调用的函数
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
pbStatus.Value = e.ProgressPercentage;
}
catch( Exception exp )
{
throw exp;
}
}
答案 0 :(得分:-2)
我猜你需要在将ProgressPercentage值分配给ProgressBar控件后立即引入一些东西,类似于 Application.DoEvents()在WinForms中所做的事情。在WPF中,您可以通过Dispatcher实现相同的目标。看看它是如何工作的,用这个来理解和实现解决方案可能需要时间。请参阅MSDN中的此代码示例 -
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public void DoEvents()
{
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
new DispatcherOperationCallback(ExitFrame), frame);
Dispatcher.PushFrame(frame);
}
public object ExitFrame(object f)
{
((DispatcherFrame)f).Continue = false;
return null;
}
但是,如果你只是想继续前进,你仍然可以在这里使用 Application.DoEvents(),但只能在导入 System.Windows.Forms.dll 之后在你的WPF项目中(这是一种丑陋的解决方案)。