我使用异步读取数据库,已经读取出来数据了,但为什么界面死了,而且也无法关闭,只能通过停止调试才能停止下来。使用的是WinForm
Code
private void Form1_Load(object sender, EventArgs e)
{
DataGridView.CheckForIllegalCrossThreadCalls = false;
}
private void BindData(IAsyncResult ar)
{
if (ar.IsCompleted)
{
SqlCommand com = (SqlCommand)ar.AsyncState;
SqlDataReader reader = com.EndExecuteReader(ar);
DataTable table = new DataTable();
table.Load(reader);
this.dgvTest.DataSource = table;
reader.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("server=.;database=logging;Integrated Security=true;Asynchronous Processing=true");
SqlCommand com = new SqlCommand("select * from Test", conn);//数据库量有6万;
conn.Open();
com.BeginExecuteReader(new AsyncCallback(BindData), com);
}
界面只能使用Invoke来调用,因为线程不同,具体可以搜索下“WINFORM UI 多线程”
.Net 下其他线程操作UI,通常用Invoke 来实现,也可以设置
Control.CheckForIllegalCrossThreadCalls = false;
见下面链接
http://blog.csdn.net/x_free/archive/2008/05/15/2447050.aspx