refactor 使用BeginExecuteReader异步加载数据

1.使用SqlCommand.ExecuteReader()方法会造成窗体假死,所以用.net2.0新增的方法BeginExecuteReader

 

代码如下:

private delegate void DataGridViewHandler(DataTable dt);

        /// <summary>
        /// 此处开始加在数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            SqlConnection conn =
                new SqlConnection("Data Source=.;Initial Catalog=Test;User Id=sa;Password=*********;Async=true");
            conn.Open();
            SqlCommand cmd = new SqlCommand("Select top 700000 * from Test", conn) {CommandTimeout = 0};
            //此处开始查询数据,执行非常耗时的工作,ProcessData为执行完成后的委托
            cmd.BeginExecuteReader(ProcessData, cmd);
            //此处不会阻塞当前线程,label2 Text会马上执行
            label2.Text = "label2 Text会马上执行";
        }

        /// <summary>
        /// 查询完成后,执行的方法
        /// </summary>
        /// <param name="ar"></param>
        private void ProcessData(IAsyncResult ar)
        {
            SqlCommand cmd = (SqlCommand) ar.AsyncState;
            using (cmd.Connection)
            {
                using (cmd)
                {
                    SqlDataReader sdr = cmd.EndExecuteReader(ar);
                    DataTable dt = new DataTable("Product");
                    dt.Load(sdr);

                    //将查询的数据,赋给dataGridView1的DataSource
                    dataGridView1.BeginInvoke(
                        new DataGridViewHandler((dtResult) => dataGridView1.DataSource = dtResult), dt);
                }
            }
        }

你可能感兴趣的:(refactor)