gpt4 book ai didi

c# - 如何将进度更改事件链接到进度栏

转载 作者:行者123 更新时间:2023-12-03 13:21:29 26 4
gpt4 key购买 nike

我有Windows窗体应用程序,它运行BackgroundWorker的类方法。

我想添加Windows窗体进度条以显示进度。

在类方法中,我有一个foreach循环,所以我希望每个循环都发送form事件

用当前百分比。

这就是我所做的:

public partial class Form1 : Form
{
Parsser inst;

public Form1()
{
InitializeComponent();
inst = new Parsser();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}


private void button2_Click(object sender, EventArgs e)
{
if (this.textBox1 != null & this.textBox2 != null)
{
if (backgroundWorker1.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync();
}
}
}



private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
inst.init(this.textBox1.Text, this.textBox2.Text);

inst.ParseTheFile();
System.Windows.Forms.MessageBox.Show("Parsing finish successfully");

}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}

}


}

`

在类里面,我这样做-
public Parsser()
{
bgReports = new BackgroundWorker();
bgReports.WorkerReportsProgress = true;
}

public void ParseTheFile()
{
Lines = File.ReadAllLines(FilePath);
this.size = Lines.Length;
foreach (string line in Lines)
{

bgReports.ReportProgress(allreadtchecked/size);

由于某种原因,它不起作用吗?

最佳答案

BackgroundWorker的引用传递给Parsser,然后使用该引用调用ReportProgrss方法

BackgroundWorker worker;

public Parsser(BackgroundWorker bg)
{
worker = bg;
}

public void ParseTheFile()
{
Lines = File.ReadAllLines(FilePath);
this.size = Lines.Length;
foreach (string line in Lines)
{
worker.ReportProgress(allreadtchecked/size);

关于c# - 如何将进度更改事件链接到进度栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7555298/

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