简体   繁体   中英

Got Cross-thread operation not valid?

My codes works fine but, when I make thread I got Cross-thread operation not valid when try to add item to ComboBox . I tried this codes in backgroundworker too but same error

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();
        }
    }
}

You can update the control from the thread its been created and can't update it from another thread.

Below is the working code to update the control from the same thread its been created from another thread.

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();
        }
    }
}

You could use a delegate to invoke the changes on the UI thread, like so

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);
    }
}

and then simply use

AddItem( ProgramType, type );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM