[英]progress bar in background worker get argument which being updated in the main thread c# wpf
我有主線程是WPF中的向導。
用戶完成設置向導的屬性后,它將處理數據。
這需要幾秒鍾,我想提出一個進度條來報告進度。
因此,我總是在主線程變量currentStep上進行設置。
我完全有thresholdStep步驟等於12。
因此,我希望進度條可以用作線程,但是也可以通過使用currentStep變量將其連接到主線程。
因此,我被后台工作人員使用過:
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 = (int)e.Argument;
backgroundWorker.ReportProgress((int)Math.Floor((decimal)(8*i)));
if (i > GeneralProperties.General.thresholdStep)
backgroundWorker.ReportProgress(100);
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progress.Value = e.ProgressPercentage;
}
private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
WindowMsg msg = new WindowMsg();
msg.Show();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (backgroundWorker.IsBusy == false)
backgroundWorker.RunWorkerAsync(GeneralProperties.General.currentStep);
}
}
另外,我從主線程中調用了背景工作者,如下所示:
MessageWithProgressBar progress = new MessageWithProgressBar();
progress.Show();
實際發生的是,DoWork僅在currentStep = 1時調用了一次,並且不會相對於主線程進行更新,該主線程也會根據其進度來更新currentStep。
有什么想法如何解決嗎?
謝謝!
如下更改您的DoWork
方法:
private void DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(100);
int i = (int)e.Argument;
do
{
i = GeneralProperties.General.currentStep;
backgroundWorker.ReportProgress((int)Math.Floor((decimal)(8 * i)));
if (i > GeneralProperties.General.thresholdStep)
backgroundWorker.ReportProgress(100);
}
while (i < GeneralProperties.General.thresholdStep);
}
只要確保您在使用GeneralProperties.General
對象時不會出現線程synchronization
問題,就可以在訪問對象時使用lock
。
更新:
對於更新問題:
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
{
progress.Value = e.ProgressPercentage;
}), null);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.