Background Worker implementation

若如初见. 提交于 2019-12-02 11:47:16

BGW is obsolete. The TPL, async/awaitand IProgress<T> can address all cases where BGW was used and more.

In this case, BGW isn't appropriate anyway. The real delay is caused by the database call, not loading the UI. To execute the database call asynchronously, you only have to use an asynchronous event handler:

private async void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
        var conString=Properties.Settings.Default.MyConnectionString;
        string query = "SELECT * FROM dbo.Liguanea_Lane2";                    

        using(var con = new SqlConnection(conString))
        using(var cmd = new SqlCommand(query, con))
        {
            await con.OpenAsync();
            var reader=await cmd.ExecuteReader();
            while (dr.Read())
            {
                string scode = dr.GetString(dr.GetOrdinal("code"));
                comboBox2.Items.Add(scode);
            }
        }
}

There are better ways to load a combo though. One improvement is to load all items in a list, then use AddRange to update the combo. AddRange already calls BeginUpdate to prevent UI updates while adding items from the list.

        var items=new List<string>();
        using(var con = new SqlConnection(conString))
        using(var cmd = new SqlCommand(query, con))
        {
            await con.OpenAsync();
            var reader=await cmd.ExecuteReader();
            while (dr.Read())
            {
                string scode = dr.GetString(dr.GetOrdinal("code"));
                list.Add(scode);
            }
        }

        comboBox2.Items.AddRange(items);

Even better, use a micro-ORM like Dapper to get rid of all this code:

using(var con = new SqlConnection(conString))
{
    await con.OpenAsync();
    var items=await con.QueryAsync<string>(query);
    comboBox2.Items.AddRange(items);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!