gpt4 book ai didi

wpf BackgroundWorker - 关于更新 UI

转载 作者:行者123 更新时间:2023-12-04 06:30:25 25 4
gpt4 key购买 nike

我使用浏览文件对话框来允许用户选择多个图像。如果选择了很多图像,正如预期的那样需要一点时间。下面是我对所选图像的处理示例。我循环遍历图像的文件路径并创建一个用户控件的实例,用户控件有一个图像控件和一些其他控件。我创建了此控件的实例,然后将其添加到关联窗口 xaml 文件中创建的现有 stackPanel。下面的示例工作正常,但我试图更好地理解 BackGroundWorker,我了解了如何设置它的基础知识,它的事件,并传回一个可以更新进度条的值,但是因为我的循环需要下面的正常运行时间将用户控件实例添加到现有的 stackPanel 中,它不会工作,因为在不同的线程中。 BackGroundWorker 是否适用于这样的示例?如果是这样,更新线程外的 ui(我的堆栈面板)的最佳方法是什么。我对 wpf 相当陌生,除了测试它只是用 int 值更新进度之外,从未使用过 BackGroundWorker,所以我希望这个问题是有道理的,如果我偏离目标,请告诉我。感谢您的任何想法。

我现在如何做的示例,它确实工作正常。

protected void myMethod(string[] fileNames) {  
MyUserControl uc;

foreach (String imagePath in fileNames) {
uc = new MyUserControl();
uc.setImage(imagePath);
stackPanel.Children.Add(uc);
progressBar.Value = ++counter;
progressBar.Refresh();
}
}

在这门课下面我有这个,所以我可以刷新进度条:
public static class extensionRefresh {  
private static Action EmptyDelegate = delegate() { };

public static void Refresh(this UIElement uiElement) {
uiElement.Dispatcher.Invoke(DispatcherPriority.Background, EmptyDelegate);
}
}

最佳答案

看看这篇文章
Building more responsive apps with the Dispatcher

Now that you have a sense of how the Dispatcher works, you might be surprised to know that you will not find use for it in most cases. In Windows Forms 2.0, Microsoft introduced a class for non-UI thread handling to simplify the development model for user interface developers. This class is called the BackgroundWorker

In WPF, this model is extended with a DispatcherSynchronizationContext class. By using BackgroundWorker, the Dispatcher is being employed automatically to invoke cross-thread method calls. The good news is that since you are probably already familiar with this common pattern, you can continue using BackgroundWorker in your new WPF projects


基本上方法是
BackgroundWorker _backgroundWorker = new BackgroundWorker();

// Set up the Background Worker Events
_backgroundWorker.DoWork += _backgroundWorker_DoWork;
_backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted;

// Run the Background Worker
_backgroundWorker.RunWorkerAsync(5000);

// Worker Method
void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Do something
}

// Completed Method
void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Doing UI stuff
if (e.Cancelled)
{
statusText.Text = "Cancelled";
}
else if (e.Error != null)
{
statusText.Text = "Exception Thrown";
}
else
{
statusText.Text = "Completed";
}
}

关于wpf BackgroundWorker - 关于更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5488444/

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