我需要在我的應用程序中使用線程,但我不知道如何執行跨線程操作。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