gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:48:01 27 4
gpt4 key购买 nike

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

为了清楚地了解正在发生的事情并考虑评论和这篇文章 here

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

后台worker设置在这里

 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 表单上“swishes”以向用户显示某些事情仍在进行中。我已经使用了后台工作的记者部分,因为我相信它可以访问主窗口线程,我希望调用方法然后从主窗口线程调用,但我不太确定

记者来了

 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;
}
}
));
}
}

}

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

我的想法是我有两个很长的过程,我要么从远程 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 progress changed 和在主窗口类中

 this.progressBar2.IsIndeterminate = true;

但是,直到 Dowork 线程完成后动画才会开始。

然后我创建了另一个后台 worker 来更新 progressbar2,它链接到主窗口上的一个按钮是可以的,但是当我试图从另一个后台 worker 或主窗口类中使用它时,它就没有运行直到 dowork 线程在第一个后台 worker 上完成

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

所以任何人都可以提供帮助吗?我猜这与线程和在错误的线程上工作等有关,但我对此一无所知。

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

伊恩

最佳答案

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

用户控件 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>

主窗口 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
}
}
}

关于c# - 如何使用 ProgressBar 更新正确实现 BackgroundWorker?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19334583/

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