我使用的是Visual Studio 2013,当我使用bw_ProgressChanged()
时,我无法弄清textBox1.AppendText()
运行两次的原因。此外bw_DoWork()
运行两次。
代码只是来自Microsoft example的复制粘贴,区别在于我使用textBox1.AppendText()
代替textBox1.Text = ""
。
代码如下所示:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void button1_Click(object sender, EventArgs e)
{
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; (i <= 10); i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500);
worker.ReportProgress((i * 10));
}
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.textBox1.AppendText(e.ProgressPercentage.ToString() + "%\n");
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
this.textBox1.AppendText("Canceled!");
}
else if (!(e.Error == null))
{
this.textBox1.AppendText("Error: " + e.Error.Message);
}
else
{
this.textBox1.AppendText("Done!");
}
}
}
textbox1文字如下所示:
10%
10%
20%
20%
30%
30%
40%
40%
50%
50%
60%
60%
70%
70%
80%
80%
90%
90%
100%
100%
10%
10%
20%
20%
30%
30%
40%
40%
50%
50%
60%
60%
70%
70%
80%
80%
90%
90%
100%
100%
Done!Done!
而不是:
10%
20%
30%
40%
50%
60%
70%
80%
90%
100%
Done!
我试图将进度直接传递给局部变量,然后将其传递给textbox1
,但它没有任何区别。任何想法为什么会发生这种情况?
答案 0 :(得分:3)
事件方法中的代码运行两次,因为您已经以某种方式订阅了ProgressChanged
事件两次。
由于我在您的代码中没有看到两个订阅,您可能已经通过设计器订阅了它(请检查Designer.cs
文件以确认),因此从构造函数中删除此行:
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
当您接触它时,请仔细检查DoWork
和RunWorkerCompleted
。您最有可能订阅这两次,这可以解释为什么您的输出打印10到100,然后再次打印相同的倍增值。