[英]Got Cross-thread operation not valid?
我的代码工作正常,但是当我创建线程时,尝试将项目添加到ComboBox
时得到了跨线程操作无效。 我也在backgroundworker
尝试了此代码,但出现相同的错误
new Thread(GetInfo).Start();
public void GetInfo()
{
while (true)
{
if (SellerControlGroup.Enabled)
{
SqlDataReader Type = new SqlCommand("select type from _Price where Service = 1", sqlCon.con).ExecuteReader();
while (Type.Read())
{
string type = Convert.ToString(Type["type"]);
ProgramType.Items.Add(type);
}
Type.Close();
}
}
}
您可以从其创建的线程中更新控件,而不能从另一个线程中更新控件。
下面是工作代码,用于从另一个线程创建的同一线程更新控件。
new Thread(GetInfo).Start();
public void GetInfo()
{
while (true)
{
if (SellerControlGroup.Enabled)
{
SqlDataReader Type = new SqlCommand("select type from _Price where Service = 1", sqlCon.con).ExecuteReader();
while (Type.Read())
{
string type = Convert.ToString(Type["type"]);
// Update control with the same thread its been created
this.Invoke((MethodInvoker)delegate()
{
ProgramType.Items.Add(type);
});
}
Type.Close();
}
}
}
您可以使用委托来调用UI线程上的更改,如下所示
delegate void AddItemDelegate(ComboBox cmb, string value);
void AddItem(ComboBox cmb, string value) {
if (cmb.InvokeRequired) {
cbm.Invoke( new AddItemDelegate( AddItem ), cmb, value );
} else {
cmb.Items.add(value);
}
}
然后简单地使用
AddItem( ProgramType, type );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.