gpt4 book ai didi

c# progressbar 不更新

转载 作者:太空狗 更新时间:2023-10-29 18:12:45 26 4
gpt4 key购买 nike

我有一个 ProgressBarWindow,上面有一个进度条和一个取消按钮,我用它来报告文件 I/O 的进度。但是,ProgressBarWindow 的 UI 线程和我的主窗口都挂起,尽管所有工作都是在后台工作程序中完成的。进度条已呈现,就像我的主窗口一样,但在后台工作人员执行操作时不会更新。在主窗口的构造函数的最后调用以下代码:

iCountLogLinesProgressBar = new ProgressBarWindow();
iCountLogLinesProgressBar.cancelButton.Click += EventCountLogLinesProgressBarCancelButtonClicked;
iCountLogLinesProgressBar.Show();

iCountLogRecords = new BackgroundWorker();
iCountLogRecords.DoWork += EventCountLogLinesDoWork;
iCountLogRecords.ProgressChanged += EventCountLogLinesProgressChanged;
iCountLogRecords.RunWorkerCompleted += EventCountLogLinesRunWorkerCompleted;
iCountLogRecords.WorkerReportsProgress = true;
iCountLogRecords.WorkerSupportsCancellation = true;
iCountLogRecords.RunWorkerAsync(new BinaryReader(File.Open(iMainLogFilename, FileMode.Open, FileAccess.Read)));

EventCountLogLinesProgressChanged() 看起来像这样:

private void EventCountLogLinesProgressChanged(object sender, ProgressChangedEventArgs e)
{
iCountLogLinesProgressBar.Value = e.ProgressPercentage;
}

这是 ProgressBarWindow 的简化版本(其余只是几个 setter ):

public partial class ProgressBarWindow : Window
{
public ProgressBarWindow()
{
InitializeComponent();
this.progressBar.Value = this.progressBar.Minimum = 0;
this.progressBar.Maximum = 100;
}

public double Value
{
get
{
return progressBar.Value;
}
set
{
this.progressBar.Value = value;
}
}
}

我已经尝试将 value setter 行包装在一个 dispatcher.invoke 委托(delegate)中,但这给了我一个堆栈溢出(我不应该有一个 dispatcher.invoke 行,因为 backgroundworker 在 UI 线程中调用 ProgressChanged,对吧? ).我检查了 msdn 并用谷歌搜索,但我似乎找不到其他人遇到这个问题。

编辑 抱歉,我没有意识到我的简化代码阻塞了 UI 线程,尽管使用了 backgroundworker,但我得到了完全相同的行为,所以我错误地认为它们是等价的。我应该提到我正在使用后台 worker :P

最佳答案

您正在阻塞 UI 线程,因此在您的循环完成之前它不会重新呈现 UI。

将后台处理移至单独的线程中,并使用适当的 Dispatcher 调用(或 BackgroundWorker)将 UI 更新调用编码回 UI 线程。

如果您的进度条真的只是一个计时器,您可以使用 Timer 类之一来更新它。

编辑:好的,现在您已经更改了代码,我觉得没问题。它应该是线程安全的,因为您只是在 UI 线程上更改 UI。您的后台 worker 肯定会定期报告进度吗?

关于c# progressbar 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3387071/

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