这是 DoWork
事件、ProgressChanged
事件和 RunWorkerCompleted
事件的代码。问题是在函数处理操作结束之前,progressBar 的速度提高了 100%。因此,当progressBar 达到100% 时,我收到错误异常,因为progressBar 不能为101%
我需要以某种方式使progressBar 根据功能进程/进度获得进度。我猜我在 DoWork
事件中的计算有问题。
在 Form1
顶部我添加了:
Int i;
在构造函数中我做了:
i = 0;
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.RunWorkerAsync();
这是
Backgroundworker
的事件:private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
//int currentLength;
//int currentIndex;
//int lastIndex = 0;
string startTag = "T256=\"";
string endTag = "\"";
int startTagWidth = startTag.Length;
//int endTagWidth = endTag.Length;
int index = 0;
h = new StreamReader(@"d:\DeponiaSplit\testingdeponias_Translated.txt");
while ((line = h.ReadLine()) != null)
{
if (index > f.LastIndexOf(startTag))
{
break;
}
int startTagIndex = f.IndexOf(startTag, index);
int stringIndex = startTagIndex + startTagWidth;
index = stringIndex;
int endTagIndex = f.IndexOf(endTag, index);
int stringLength = endTagIndex - stringIndex;
if (stringLength != 0)
{
string test = f.Substring(stringIndex, stringLength);
f = f.Substring(0, stringIndex) + line + f.Substring(stringIndex + stringLength);
if (listBox1.InvokeRequired)
{
textBox1.Invoke(new MethodInvoker(delegate { textBox1.Text = line; }));
}
i = i + 1;
System.Threading.Thread.Sleep(500);
worker.ReportProgress((i * 1));
}
}
h.Close();
StreamWriter w = new StreamWriter(@"D:\New folder (24)\000004aa.xml");
w.AutoFlush = true;
w.Write(f);
w.Close();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//this.progressBar1.Text = (e.ProgressPercentage.ToString() + "%");
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
this.progressBar1.Text = "Canceled!";
}
else if (!(e.Error == null))
{
this.progressBar1.Text = ("Error: " + e.Error.Message);
}
else
{
this.progressBar1.Text = "Done!";
}
}
为什么它不能正常工作?
使用 FileStream 工作
现在我想向progressBar 添加一个标签,该标签将显示
%
,标签将根据progressBar 移动我不想禁用progressBar 绿色进度只是为了添加%
并以百分比显示数字。所以在
ProgressChanged
事件中我做了:private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label3.Text = (e.ProgressPercentage.ToString() + "%");
}
但它不起作用 -
label13
不会只移动 % 更改为 1。我想看到类似 1%...2%...3%... 之类的东西。我该怎么做? 最佳答案
为什么不使用 File.ReadAllLines
,它返回一个字符串数组。您可以将您的进度报告为您正在处理的行占总行数的百分比:
string[] lines = File.ReadAllLines(@"d:\DeponiaSplit\testingdeponias_Translated.txt");
// ...
worker.ReportProgress(i * 100 / lines.Length);
关于c# - 我正在尝试使用 backgroundworker 但它不起作用 - 为什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10374469/