嗨,我有以下代码将一些项目添加到组合框中 当我在线程中执行代码时,我有以下异常"特定强制转换无效"但是在主窗体线程中执行此操作时没有例外。知道如何解决这个问题吗?
Control.CheckForIllegalCrossThreadCalls = false;
//Auto Complete
comboBox3.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox3.AutoCompleteSource = AutoCompleteSource.ListItems;
//no specific formatting
comboBox3.FormattingEnabled = true;
Thread th1 = new Thread(() =>
{
try
{
//# Code Start
//Some Text
String[] TicketStatus = new string[] { "a", "b", "c", "d", "e" };
//Throw Exception "Specific cast is not valid"
comboBox3.Items.AddRange(TicketStatus);
//# Code End
}
catch (Exception c) { MessageBox.Show(c.Message); }
});
th1.Start();
像这样没有例外
Control.CheckForIllegalCrossThreadCalls = false;
//Auto Complete
comboBox3.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox3.AutoCompleteSource = AutoCompleteSource.ListItems;
//no specific formatting
comboBox3.FormattingEnabled = true;
//# Code Start
//Some Text
String[] TicketStatus = new string[] { "a", "b", "c", "d", "e" };
//Throw Exception "Specific cast is not valid"
comboBox3.Items.AddRange(TicketStatus);
//# Code End
不能从 UI 线程以外的线程访问 UI 元素。
您必须将资源库代码编组回 UI 线程。
使用InvokeRequired
执行此操作。