gpt4 book ai didi

c# - 为什么WPF中的BackgroundWorker需要Thread.Sleep来更新UI控件?

转载 作者:行者123 更新时间:2023-11-30 14:04:03 26 4
gpt4 key购买 nike

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
BackgroundWorker bgWorker;
Action<int> myProgressReporter;

public Window1()
{
InitializeComponent();
bgWorker = new BackgroundWorker();
bgWorker.DoWork += bgWorker_Task;
bgWorker.RunWorkerCompleted += myWorker_RunWorkerCompleted;

// hook event to method
bgWorker.ProgressChanged += bgWorker_ReportProgress;

// hook the delegate to the method
myProgressReporter = updateProgress;

bgWorker.WorkerReportsProgress = true;

}

private void myWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
object result;
result = e.Result;
MessageBox.Show(result.ToString());
progressBar1.Value = 0;
button1.IsEnabled = true;
}

private void bgWorker_ReportProgress(object sender, ProgressChangedEventArgs e)
{
System.Windows.Threading.Dispatcher disp = button1.Dispatcher;
disp.BeginInvoke(myProgressReporter,e.ProgressPercentage);
//Dispatcher.BeginInvoke(myProgressReporter, DispatcherPriority.Normal, e.ProgressPercentage);
}

private void updateProgress(int progressPercentage)
{
progressBar1.Value = progressPercentage;
}

private void bgWorker_Task(Object sender, DoWorkEventArgs e)
{
int total = 1000;
for (int i = 1; i <= total; i++)
{
if (bgWorker.WorkerReportsProgress)
{
int p = (int)(((float)i / (float)total) * 100);
bgWorker.ReportProgress(p);
}
Thread.Sleep(1); // Without Thread.Sleep(x) the main thread freezes or gives stackoverflow exception,
}

e.Result = "Completed";
}

private void button1_Click(object sender, RoutedEventArgs e)
{
if(!bgWorker.IsBusy)
bgWorker.RunWorkerAsync("This is a background process");
button1.IsEnabled = false;
}
}
}

最佳答案

因为在您的(人工)场景中,您向主线程发送了 1000 个更新请求。
它没有时间进行空闲循环(进行屏幕更新所必需的)。

但是(感谢 TerrorAustralis),您应该从合并 bgWorker_ReportProgress 和 myProgressReporter 方法开始。您现在正在同步两次,这可能是 stackoverflow 的原因。调度 UpdateProgress 事件是 Backgroundworker 的主要功能之一:

private void bgWorker_ReportProgress(object sender, ProgressChangedEventArgs e)
{
//System.Windows.Threading.Dispatcher disp = button1.Dispatcher;
//disp.BeginInvoke(myProgressReporter,e.ProgressPercentage);
progressBar1.Value = progressPercentage; // safe because we're on the main Thread here
}

关于c# - 为什么WPF中的BackgroundWorker需要Thread.Sleep来更新UI控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3019185/

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