如何使用ProgressBar更新正确实现BackgroundWorker?

– 更新 – 14/10也问了这个问题

给出一些清晰的想法,并考虑到这里的评论和这篇文章

我现在真正想要做的就是调用一个带有进度条的新窗体,让它运行和设置animation,而我的后台线程将我的长进程运行到数据库,然后调用一个closures窗体事件

后台工作人员在这里设置

public partial class MainWindow : Window { //Declare background workers BackgroundWorker bw = new BackgroundWorker(); BackgroundWorker bwLoadCSV = new BackgroundWorker(); BackgroundWorker bwProgressBar = new BackgroundWorker(); 

然后代表在这里添加

  public MainWindow() { bwLoadCSV.WorkerReportsProgress = true; bwLoadCSV.WorkerSupportsCancellation = true; bwLoadCSV.DoWork += new DoWorkEventHandler(bwLoadCSV_DoWork); bwLoadCSV.ProgressChanged += new ProgressChangedEventHandler(bwLoadCSV_ProgressChanged); bwLoadCSV.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwLoadCSV_RunWorkerCompleted); 

这个调用是从主窗口类来的

  private void CSV_Load_Click(object sender, RoutedEventArgs e) ///Function to read csv into datagrid /// { //Turn Cursor to wait System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; //Test connection to sql server if (CHHoursDataProvider.IsDatabaseOnline() == false) { System.Windows.Forms.MessageBox.Show("Can not establish contact with sql server" + "\n" + "Contact IT", "Connection Error"); //Set UI picture return; } //Set a control to update the user here tbLoadDgStat.Visibility = Visibility.Visible; tbLoadDgStat.Text = "Getting data templete from Database..."; string FilePath = txFilePath.Text; if (bwLoadCSV.IsBusy != true) { //load the context object with parameters for Background worker bwCSVLoadContext Context = new bwCSVLoadContext(); Context.Site = cBChSite.Text; Context.FilePath = txFilePath.Text; Context.FileName = fileTest; Context.Wageyear = cbWageYear.Text; Context.Startdate = ((DateTime)dpStartDate.SelectedDate); Context.Enddate = ((DateTime)dpEndDate.SelectedDate); bwLoadCSV.RunWorkerAsync(Context); } 

后台工作者的工作是

 private void bwLoadCSV_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; bwCSVLoadContext Context = e.Argument as bwCSVLoadContext; worker.ReportProgress((10)); if ((worker.CancellationPending == true)) { e.Cancel = true; } else { // Perform a time consuming operation and report progress load csv into datagrid. 

要报告背景工作,我这样做。 这是我正在试图加载一个新的窗体调用ProgressDialog,它有一个进度条,我尝试设置为不确定,所以它只是“摆动”我的ProgressDialogeforms显示用户仍在继续。 我已经使用了后台工作的记者部分,因为我相信它可以访问主窗口线程,我希望调用方法然后从主窗口线程调用,但我不太确定

这是记者

  private void bwLoadCSV_ProgressChanged(object sender, ProgressChangedEventArgs e) { this.Dispatcher.Invoke((MethodInvoker)delegate { tbLoadDgStat.Visibility = Visibility.Visible; }); //tbLoadDgStat.Visibility = Visibility.Visible; //this.progressBar1.Value = e.ProgressPercentage;//This works but pauses on long steps if (e.ProgressPercentage == 10) { //Try to open a new form with a class ProgressDialog and set the progressbar // on the frm to IsIndeterminate=true //THIS IS NOT WORKING this.Dispatcher.BeginInvoke (new Action(() => { ProgressDialog progressDialog = new ProgressDialog(); progressDialog.SetIndeterminate(true); })); //this updates the main form OK this.Dispatcher.Invoke((MethodInvoker)delegate { tbLoadDgStat.Text = "Getting data templete from Database..."; }); } else if (e.ProgressPercentage == 20) { this.Dispatcher.Invoke((MethodInvoker)delegate { tbLoadDgStat.Text = "Data template retrieved..."; }); } else { if (e.ProgressPercentage % 10 == 0) { this.Dispatcher.Invoke((MethodInvoker)delegate { tbLoadDgStat.Text = "Adding Data..." + e.ProgressPercentage.ToString() + "%"; }); } } 

最后是ProgressDialog Form的xaml,它是类

 <Window x:Class="Test_Read_CSV.ProgressDialog" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Progress Dialog" Height="115" Width="306" Name="ProgressPopup"> <Grid> <ProgressBar Height="31" HorizontalAlignment="Left" Margin="12,33,0,0" Name="progressBar1" VerticalAlignment="Top" Width="250" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="7,4,0,0" Name="tbEvent" VerticalAlignment="Top" Width="254" IsReadOnly="True" IsEnabled="False" /> </Grid> 

 /// <summary> /// Interaction logic for ProgressDialog.xaml /// </summary> public partial class ProgressDialog : Window { public ProgressDialog() { WindowStartupLocation = WindowStartupLocation.CenterScreen; InitializeComponent(); } public ProgressDialog(String Purpose) { InitializeComponent(); tbEvent.Text = Purpose; WindowStartupLocation = WindowStartupLocation.CenterScreen; } public void UpdateProgress(int progress) { progressBar1.Dispatcher.BeginInvoke( new Action(() => { progressBar1.Value = progress; } )); } public void SetIndeterminate(bool isIndeterminate) { progressBar1.Dispatcher.BeginInvoke( new Action(() => { if (isIndeterminate) { progressBar1.IsIndeterminate = true; } else { progressBar1.IsIndeterminate = false; } } )); } } } 

我已经阅读并完成了一些关于后台工作者的教程,甚至还有一些关于线程的教程,但似乎无法得到我想要的结果

这个想法是我有两个长的进程,我要么从我的远程bd得到一个数据表复制,或者我从我的wpf应用程序(.net 4)更新数据库。 当进程正在运行时,我想要一个进度条控件并对其进行更新,因为明确指出某些工作正在进行。 所以我做了在后台工作人员通常的报告进度例程,它的工作….但是,在我的主持线程中,我有这个命令

 CHHoursDataProvider CH = new CHHoursDataProvider(); oTable = CH.CloneCHHours(); 

这与db的通信是,这个命令需要一个很好的60 – 90秒的VPN远程连接,所以即使我这样做

 CHHoursDataProvider CH = new CHHoursDataProvider(); worker.ReportProgress((10)); oTable = CH.CloneCHHours(); worker.ReportProgress((20)); 

主窗口仍然看起来冻结,就像它已经崩溃了!

所以我只想在开始调用后台工作时设置一个进度条运行,并保持运行直到任务结束。 这就是我完成我的第一个项目所需要做的,三天之后我仍然无法摆脱困境!

所以我试了下

在bw进度改变和主窗口类中

  this.progressBar2.IsIndeterminate = true; 

但是,直到Dowork线程完成后,animation才会启动。

然后我创build了另一个后台工作来更新progressbar2,它连接到主窗口上的一个button是可以的,但只要我尝试从另一个后台工作者或从主窗口类使用它,直到dowork线程在第一个后台工作完成

然后我试图按照调用方法,但真的迷上了!

所以任何人都可以帮助,我可以猜测这是与线程和线程工作的东西有关,但我做了什么,我不知道。

我可以根据需要发布更多的代码

伊恩

由于您还没有显示完整的BackgroundWorker代码,因此我无法确定您是否已经正确实施了它。 因此,我所能做的就是向您展示一个更新ProgressBar控件的简单工作示例:

UserControl XAML:

 <UserControl x:Class="WpfApplication1.Views.TestView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" Loaded="UserControl_Loaded"> <ProgressBar x:Name="progressBar" Height="25" Margin="20" Minimum="0" Maximum="50" /> </UserControl> 

MainWindow XAML:

 <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Views="clr-namespace:WpfApplication1.Views" Title="MainWindow" Height="350" Width="525"> <Views:TestView /> </Window> 

后面的UserControl代码:

 using System.ComponentModel; using System.Threading; using System.Windows; using System.Windows.Controls; namespace WpfApplication1.Views { public partial class TestView : UserControl { private BackgroundWorker backgroundWorker = new BackgroundWorker(); public TestView() { InitializeComponent(); backgroundWorker.WorkerReportsProgress = true; backgroundWorker.ProgressChanged += ProgressChanged; backgroundWorker.DoWork += DoWork; // not required for this question, but is a helpful event to handle backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted; } private void UserControl_Loaded(object sender, RoutedEventArgs e) { backgroundWorker.RunWorkerAsync(); } private void DoWork(object sender, DoWorkEventArgs e) { for (int i = 0; i <= 100; i++) { Thread.Sleep(100); backgroundWorker.ReportProgress(i); } } private void ProgressChanged(object sender, ProgressChangedEventArgs e) { // This is called on the UI thread when ReportProgress method is called progressBar.Value = e.ProgressPercentage; } private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // This is called on the UI thread when the DoWork method completes // so it's a good place to hide busy indicators, or put clean up code } } }