gpt4 book ai didi

c# - BackgroundWorker 的进度条不工作

转载 作者:太空宇宙 更新时间:2023-11-03 14:54:34 24 4
gpt4 key购买 nike

BackgroundWorker 的进度条在执行某些任务时不会更新。我想要达到的是进度条在遍历 DirectoryInfo 中的每个文件时移动。假设我们有 20 个“.sql”文件,而第一个文件完成它应该是 5%、10% 等等。这是我的代码。

private void CSV_Click(object sender, RoutedEventArgs e)
{
try
{
btnExtract.IsEnabled = false;
workerextract.RunWorkerAsync();

}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}

private void workerextract_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
try
{
this.Dispatcher.Invoke(() =>
{

DirectoryInfo di = new DirectoryInfo(txtQueryfolder.Text);
files = di.GetFiles("*.sql").Count();
currentfile = 0;

foreach (FileInfo fi in di.GetFiles("*.sql"))
{
// Open the text file using a stream reader.
using (StreamReader sr = new StreamReader(fi.FullName))
{
// Read the stream to a string, and write the string to the console.
string line = sr.ReadToEnd();

//System.Windows.MessageBox.Show(line);
ExtractToCSV(line, System.IO.Path.GetFileNameWithoutExtension(fi.Name));
currentfile++;
}
int percentage = (currentfile + 1) * 100 / files;
workerextract.ReportProgress(percentage);
}

});

}
catch(Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}

private void workerextract_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBarExtract.Value = e.ProgressPercentage;
}

private void workerextract_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnExtract.IsEnabled = true;
System.Windows.MessageBox.Show("CSV Data extraction finished!");
}

我发现

private void workerextract_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)

在 100% 时最后调用一次。还有,

private void workerextract_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

从未调用过,因为我在最后没有看到消息框。

所以,我想我在这里做错了什么,你能指导我正确的方法吗?

最佳答案

问题在于将整个 DoWork 包装在 Dispatcher.Invoke 中。我只需要包装那些与 UI 交互的代码。所以我适本地更改了代码并且它起作用了。

 private void workerextract_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
try
{
this.Dispatcher.Invoke(() =>
{
di = new DirectoryInfo(txtQueryfolder.Text);
});
files = di.GetFiles("*.sql").Count();
currentfile = 0;

foreach (FileInfo fi in di.GetFiles("*.sql"))
{
// Open the text file using a stream reader.
using (StreamReader sr = new StreamReader(fi.FullName))
{
// Read the stream to a string, and write the string to the console.
string line = sr.ReadToEnd();

this.Dispatcher.Invoke(() =>
{
//System.Windows.MessageBox.Show(line);
ExtractToCSV(line, System.IO.Path.GetFileNameWithoutExtension(fi.Name));
});

currentfile++;
}
int percentage = (currentfile + 1) * 100 / files;
workerextract.ReportProgress(percentage);
}
}
catch(Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}

感谢大家指明方向。

关于c# - BackgroundWorker 的进度条不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50246639/

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