異步讀取數據庫,在數據綁定的時候會出現點問題,就是窗體界面會無法關閉,要結束任務才能結束進程。例如下面代碼
首先按習慣的方法,設定線程更新UI
a2.CheckForIllegalCrossThreadCalls = false; //a2為窗體名稱
下面的代碼就是從數據庫裡取得數據並綁定
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con;
SqlCommand com;
try
{
con = new SqlConnection("UID=sa;Password=123;Initial Catalog=AD;Data Source=192.168.1.1;Asynchronous Processing=true");
con.Open();
com = new SqlCommand("select top 100 * from tb_user", con);
com.BeginExecuteReader(new AsyncCallback(delDataBin), com);
}
catch (Exception ex)
{
MessageBox.Show("程序發生錯誤,信息: " + ex.Message);
}
}
private void delDataBin(IAsyncResult ar)
{
if (ar.IsCompleted)
{
SqlCommand com = (SqlCommand)ar.AsyncState;
SqlDataReader dr = com.EndExecuteReader(ar);
DataTable dt = new DataTable();
dt.Load(dr);
dr.Close();
this.dataGridView1.DataSource = dt; //綁定數據
}
}
到這裡完成的綁定的工作,運行查看一下效果,其實這樣是會出現窗體假死的現象。
下面通過Invoke 來實現
首先聲明委托 public delegate void updateDG(DataTable dt);
然後通過dataBin來綁定DataGridView
public void dataBin(DataTable dt)
{
dataGridView1.DataSource = dt;
return;
}
在線程裡面調用下面方法
//綁定數據
if (this.InvokeRequired)
{
updateDG ur = new updateDG(dataBin);
this.Invoke(ur, dt);
}
完整的代碼如下:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con;
SqlCommand com;
try
{
con = new SqlConnection("UID=sa;Password=123;Initial Catalog=AD;Data Source=192.168.1.1;Asynchronous Processing=true");
con.Open();
com = new SqlCommand("select top 100 * from tb_user", con);
com.BeginExecuteReader(new AsyncCallback(delDataBin), com);
}
catch (Exception ex)
{
MessageBox.Show("程序發生錯誤,信息: " + ex.Message);
}
}
private void delDataBin(IAsyncResult ar)
{
if (ar.IsCompleted)
{
SqlCommand com = (SqlCommand)ar.AsyncState;
SqlDataReader dr = com.EndExecuteReader(ar);
DataTable dt = new DataTable();
dt.Load(dr);
dr.Close();
//this.dataGridView1.DataSource = dt;//綁定數據
if (this.InvokeRequired)
{
updateDG ur = new updateDG(dataBin);
this.Invoke(ur, dt);
}