【发布时间】:2016-06-01 11:21:37
【问题描述】:
我正在使用 WPF,并且我的主线程是 GUI(向导)。
当用户在向导上单击完成时,它会打开第二个线程,显示后台工作人员中使用的用户进度条。
在我做的主线程中:
MessageWithProgressBar progress = new MessageWithProgressBar();
progress.Show();
createFilesInA();
createFilesInB();
createFilesInC();
createFilesInD();
createFilesInE();
createFilesInF();
createFilesInG();
createFilesInH();
createFilesInI();
createFilesInJ();
createFilesInK();
在每个 createFiles 方法中,我将名为 currentStep 的静态变量递增 1,我在后台工作程序中使用它,如下所述。
我在后台工作:
public partial class MessageWithProgressBar : Window
{
private BackgroundWorker backgroundWorker = new BackgroundWorker();
public MessageWithProgressBar()
{
InitializeComponent();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.ProgressChanged += ProgressChanged;
backgroundWorker.DoWork += DoWork;
backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
}
private void DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(100);
int i = GeneralProperties.General.currentStep;
if (i > GeneralProperties.General.thresholdStep)
{
progress.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new DispatcherOperationCallback(delegate
{
progress.Value = 100;
title.Content = progress.Value.ToString();
return null;
}), null);
return;
}
else
{
progress.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new DispatcherOperationCallback(delegate
{
progress.Value = (int)Math.Floor((decimal)(8 * i));
progressLabel.Text = progress.Value.ToString();
return null;
}), null);
}
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progress.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new DispatcherOperationCallback(delegate
{
progress.Value = e.ProgressPercentage;
return null;
}), null);
}
private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progress.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new DispatcherOperationCallback(delegate
{
progress.Value = 100;
title.Content = progress.Value.ToString();
return null;
}), null);
WindowMsgGenDB msg = new WindowMsgGenDB();
msg.Show();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (backgroundWorker.IsBusy == false)
{
backgroundWorker.RunWorkerAsync();
}
}
}
主线程更新了名为 currentStep 的变量,第二个线程使用它来报告主线程的进度。
主线程的操作需要几秒钟(不超过15秒)
我有两个问题:
我只在currentStep=2(那么进度为16)然后进度为100时才在进度条上看到,而且我看不到每一步
一开始,进度条卡住了,好像卡住了。
(也许它从主线程连接到调用progress.Show()?)
谢谢!
【问题讨论】:
-
您是否通过绑定设置进度条的值?还是直接?
-
直接@Nudity。见上面的代码。
-
是的 ^^ - 当前步长每次迭代都增加 1?
-
@Nudity 是的,currentStep 从 1 变为 thresholdStep = 12。progressBar.Value 从 8 变为 96,然后由等式 8*i 变为 100,而 i 由 currentStep 改变。
-
这里没有增加
i并且从不使用ProgressChanged,因为你从不调用ReportProgress。所有这些代码工作者要做的就是将进度条设置为 100 或 x 8,然后完成。如果这不是您所看到的,那么您需要提供minimal reproducible example。
标签: c# wpf multithreading backgroundworker