我需要在我的应用程序中使用线程,但我不知道如何执行跨线程操作。C#.NET中的线程和交叉线程,如何从另一个线程中更改ComboBox数据?
我希望能够更改窗体对象的文本(在这种情况下,组合框),从另一个线程,我得到的错误:
Cross-thread operation not valid: Control 'titlescomboBox' accessed from a thread other than the thread it was created on.
我真的不知道如何使用调用和开始调用函数,所以即时通讯真的寻找一个死的简单的例子和解释,所以我可以了解这一点。
另外,任何新手教程都会很棒,我发现了一些,但它们都非常不同,我不明白我需要做什么来执行跨线程操作。
下面是代码:
// Main Thread. On click of the refresh button
private void refreshButton_Click(object sender, EventArgs e)
{
titlescomboBox.Items.Clear();
Thread t1 = new Thread(updateCombo);
t1.Start();
}
// This function updates the combo box with the rssData
private void updateCombo()
{
rssData = getRssData(channelTextBox.Text); // Getting the Data
for (int i = 0; i < rssData.GetLength(0); i++) // Output it
{
if (rssData[i, 0] != null)
{
// Cross-thread operation not valid: Control 'titlescomboBox'
// accessed from a thread other than the thread it was created on.
titlescomboBox.Items.Add(rssData[i, 0]); // Here I get an Error
}
titlescomboBox.SelectedIndex = 0;
}
}
这正是我所需要的,这有助于我理解这个概念好一点! – Anil
+1,用于扩展方法。我也在我的回答中推荐它。 –
就像一个说明,对于ToolStripStatusLabel&ToolStripProgressBar等StatusStrip控件,应该在StatusStrip上调用包含ToolStrip控件的调用。 – jnoreiga