非同步讀取資料庫,在資料繫結的時候會出現點問題,就是表單介面會無法關閉,要結束任務才能結束進程。例如下面代碼
首先按習慣的方法,設定線程更新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);
}
}
}
public delegate void updateDG(DataTable dt);
public void dataBin(DataTable dt)
{
dataGridView1.DataSource = dt;
return;
}
查運行查看一下,你就會發現結果了