我喜欢填充数组"数字"在" treeView1"控制。 如果我不使用backgroundWorker控件,一切正常。
如果我使用backgroundWorker,则treeView1中不会显示任何内容。看起来代码卡在foreach循环中。
//Step1
private void button1_Click(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
backgroundWorker1.RunWorkerAsync();
button1.Enabled = false;
}
//Step2
private void backgroundWorker1_DoWork_1(object sender, DoWorkEventArgs e)
{
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
foreach (int element in numbers)
{
treeView1.Nodes.Add(element.ToString());
}
button1.Enabled = true;
}
我尝试了下面建议的所有内容,但仍然没有显示任何内容
//Step1
private void button1_Click(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = true;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.RunWorkerAsync();
button1.Enabled = false;
}
//Step2
private void backgroundWorker1_DoWork_1(object sender, DoWorkEventArgs e)
{
this.treeView1.Nodes.Clear();
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
treeView1.BeginUpdate();
foreach (int element in numbers)
{
treeView1.Nodes.Add(element.ToString());
}
treeView1.EndUpdate();
button1.Enabled = true;
treeView1.Refresh();
}
感谢Banjamin现在所有工作:)
//Step1
private void button1_Click(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.RunWorkerAsync();
button1.Enabled = false;
}
//Step2
private void backgroundWorker1_DoWork_1(object sender, DoWorkEventArgs e)
{
this.treeView1.Nodes.Clear();
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
treeView1.Invoke((Action)delegate
{
foreach (int element in numbers)
{
treeView1.Nodes.Add(element.ToString());
}
});
treeView1.EndUpdate();
//button1.Enabled = true;
treeView1.Refresh();
System.Windows.Forms.MessageBox.Show("Completed");
button1.Invoke((Action)delegate { button1.Enabled = true; });
}
答案 0 :(得分:0)
如果您在调试器中运行代码,您将获得一个异常弹出窗口,为您提供有关出错的更多详细信息:
附加信息:正在从错误的线程调用正在对此控件执行的操作。使用Control.Invoke或Control.BeginInvoke对正确的线程进行Marshal来执行此操作。
您应该始终从应用程序的主(或窗口)线程更新UI。正确的代码是:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
treeView1.Invoke((Action)delegate
{
foreach (int element in numbers)
{
treeView1.Nodes.Add(element.ToString());
}
});
button1.Invoke((Action) delegate { button1.Enabled = true; });
}
通过在treeView1和button1上使用Invoke方法,确保使用正确的线程来更新UI。