编辑:我通过在代码中创建后台工作程序而不是在设计中拖放来解决问题。
现在我知道如何使用后台工作者了。
问题
这是我第一次使用BGWorker,所以这是我的问题......
但文本框确实会更新。
我做错了吗?
守则
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace BGWorker
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
progressBar1.Minimum = 0;
progressBar1.Value = 0;
progressBar1.Maximum = 100;
}
private void button1_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
textBox1.AppendText(i.ToString());
textBox1.AppendText("\n");
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
label1.Text = e.Error.Message;
}
else
{
label1.Text = "All Done !";
Cursor.Current = Cursors.Default;
}
}
}
}
感谢。
答案 0 :(得分:1)
我同意pst。
您的if语句段应包含最常见的路径,其中else的路径最小。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 100; i++)
{
sb.AppendLine(i.ToString());
backgroundWorker1.ReportProgress(i);
}
e.Result = sb.ToString();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error == null)
{
textbox1.Text = e.Result.ToString();
label1.Text = "All Done !";
Cursor.Current = Cursors.Default;
}
else
{
label1.Text = e.Error.Message;
}
}