c#異步讀取數(shù)據(jù)庫與異步更新ui的代碼實現(xiàn)
異步讀取數(shù)據(jù)庫,在數(shù)據(jù)綁定的時候會出現(xiàn)點問題,就是窗體界面會無法關閉,要結束任務才能結束進程。例如下面代碼
首先按習慣的方法,設定線程更新UI
a2.CheckForIllegalCrossThreadCalls = false; //a2為窗體名稱
下面的代碼就是從數(shù)據(jù)庫里取得數(shù)據(jù)并綁定
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("程序發(fā)生錯誤,信息: " + 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; //綁定數(shù)據(jù)
}
}
到這里完成的綁定的工作,運行查看一下效果,其實這樣是會出現(xiàn)窗體假死的現(xiàn)象。
下面通過Invoke 來實現(xiàn)
首先聲明委托 public delegate void updateDG(DataTable dt);
然后通過dataBin來綁定DataGridView
public void dataBin(DataTable dt)
{
dataGridView1.DataSource = dt;
return;
}
在線程里面調用下面方法
//綁定數(shù)據(jù)
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("程序發(fā)生錯誤,信息: " + 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;//綁定數(shù)據(jù)
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;
}
查運行查看一下,你就會發(fā)現(xiàn)結果了
相關文章
Visual Studio C#創(chuàng)建windows服務程序
用Visual C#創(chuàng)建Windows服務不是一件困難的事,本文就將指導你一步一步創(chuàng)建一個Windows服務并使用它,本文主要介紹了Visual Studio C#創(chuàng)建windows服務程序,感興趣的可以了解一下2024-01-01

