1. 程式人生 > >C# 非同步執行SQL語句

C# 非同步執行SQL語句

非同步執行SQL語句,試下就明白,無需解釋

         /// <summary>
        /// 按鈕事件 非同步執行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            string strSql = "SELECT c1 ,c2 FROM  T1;" +
                            "WAITFOR DELAY '0:0:3';";
            AsyncExecuteNonQuery(strSql, CallbackAsyncExecuteNonQuery);
        }
 
       /// <summary>
        /// 非同步執行SQL。 
        /// </summary>
        /// <param name="sqlText">要執行的SQLText</param>
        /// <param name="callBack">回執行監控事件</param>
        public static void AsyncExecuteNonQuery(string sqlText, AsyncCallback callBack)
        {
            //關閉資料庫連線要在callback中關閉,因為是非同步操作
            SqlConnection connection = null;
            try
            {
                connection = new SqlConnection();
                connection.ConnectionString = "Data Source=192.168.1.15;Initial Catalog=TestDB;user id=sa;password=123;Max Pool Size=200;Min Pool Size=5;Pooling=true;Connection Timeout=50;Asynchronous Processing=true";
                SqlCommand cmd = connection.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = sqlText;
                connection.Open();
                cmd.BeginExecuteNonQuery(callBack, cmd); //開始執行SQL語句
            }
            catch (Exception ex)
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }
        }
        /// <summary>
        ///  執行非同步SQL 回撥方法 
        /// </summary>
        /// <param name="callBack"></param>
        public static void CallbackAsyncExecuteNonQuery(IAsyncResult callBack)
        {
            SqlCommand cmm = null;
            try
            {
                cmm = (SqlCommand)callBack.AsyncState;
                if (cmm == null)
                {
                    return;
                }
                cmm.EndExecuteNonQuery(callBack); //執行完畢
            }
            catch (Exception ex)
            {
                if (cmm != null)
                {
                    //非同步執行SQL異常
                    cmm.Dispose();
                }
                else
                {
                    //非同步執行SQL異常
                }
            }
            finally
            {
                if (cmm != null && cmm.Connection != null && cmm.Connection.State != ConnectionState.Closed)
                {
                    cmm.Dispose();
                    cmm.Connection.Close();
                }
            }
        }