[英]Cross-thread operation not valid in background worker c#
我想要一個在后台工作程序中運行的代碼,但遇到了這個錯誤:
'跨線程操作無效:控制'metroComboBox1'從創建它的線程以外的線程訪問。
private void metroRename_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
backgroundWorker1.CancelAsync();
backgroundWorker1.RunWorkerAsync(metroComboBox1.Text);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
this.Invoke((MethodInvoker)delegate ()
{
string text = metroComboBox1.Text;
});
if (metroComboBox1.SelectedItem == "TITLE") //error here
{
//some code here
}
}
如何在后台工作人員中使用組合框?
您也應該將條件置於Invoke
調用下,例如
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
this.Invoke((MethodInvoker)delegate()
{
string text = metroComboBox1.Text;
if (metroComboBox1.SelectedItem == "TITLE")
{
//some code here
}
});
}
這是有關此問題的現有線程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.