异步执行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();
}
}
}