异步查询

   public class QueryHelper
    {

        private delegate void DataGridViewHandler(DataTable dt);

        public DataGridView dataGridView { get; set; }
        public void GetData(string sql)
        {
            //得到链接,用你自己的链接串即可
            IDbConnection con = DBConPool.GetDbProvider(false, DbType.SqlServer, DbName.MainDb);
            SqlConnection conn = con as SqlConnection;
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            SqlCommand sqlCommand = new SqlCommand(sql, conn) { CommandTimeout = 0 };
            //执行耗时查询,AsyncProcess:执行完后讲结果推送到AsyncProcess
            sqlCommand.BeginExecuteReader(AsyncProcess, sqlCommand);
        }


        /// <summary>
        /// 异步执行
        /// </summary>
        /// <param name="ar"></param>
        private void AsyncProcess(IAsyncResult  asyncResult)
        {
            SqlCommand sqlCommand = (SqlCommand)asyncResult.AsyncState;
            using (sqlCommand.Connection)
            {
                using (sqlCommand)
                {
                    SqlDataReader sdr = sqlCommand.EndExecuteReader(asyncResult);
                    DataTable dt = new DataTable("info");
                    dt.Load(sdr);
                    //dataGridView1绑定数据
                    dataGridView.BeginInvoke(
                        new DataGridViewHandler((dtResult) => dataGridView.DataSource = dtResult), dt);
                }
            }
        }
}

 

posted on 2020-09-14 20:48  无觉-李敏  阅读(397)  评论(0编辑  收藏  举报