簡體   English   中英

得到了跨線程操作無效嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM