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

时间:2013-10-12 13:11:36

标签: c# wpf multithreading backgroundworker

-Updated - 14/10 也问了这个question

要清楚地了解正在发生的事情,并考虑评论和本文here

我现在真正想做的是调用一个带有进度条的新表单,并在我的背景线程运行我的长进程到数据库然后调用一个关闭表单事件时运行并设置动画

后台工作人员在这里设置

 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,它上面有一个进度条,我尝试将其设置为Indeterminable,因此它只是在我的ProgressDialoge表单中“sw”“以显示用户仍在进行的操作。我已经使用了背景工作的记者部分,因为我相信它可以访问主窗口线程,我希望然后从主窗口线程调用invoke方法,但我不是很确定

这是记者

 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表单的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)更新数据库。在进程运行的过程中,我想要一个进度条控件并对其进行更新,这是为了明确表明某些工作正在进行中。所以我在后台工作程序中执行了通常的报告进度例程并且它可以工作....但是,在我的dowork线程中我有这个命令

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

这与db的通信是这样的,并且这个命令在vpn远程连接上需要60到90秒,所以即使我这样做了

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

主窗口仍然看起来很冷,就像它已经崩溃了一样!

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

所以我尝试了以下

在bw进度改变并在主窗口类

 this.progressBar2.IsIndeterminate = true;

然而动画在Dowork线程完成之前不会启动。

然后我创建了另一个后台工作者来更新progressbar2,它链接到主窗口上的一个按钮就可以了,但是一旦我尝试从其他后台工作者或主窗口类中使用它就没有运行直到第一个背景工作者完成了dowork线程

然后我尝试遵循一个调用方法,但真的迷路了!

所以任何人都可以帮助我猜它是与线程和错误的线程等工作有关但我做了什么我不知道。

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

伊恩

1 个答案:

答案 0 :(得分:14)

由于您没有显示完整的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++)
            {
                // Simulate long running work
                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
        }
    }
}