Asynchronous Commands in ADO.NET Whidbey Example #1

Here is some example code I put together to using the BeginExecuteNonQuery() command.

using System.Data.SqlClient; //I updated this after the initial post so that I would follow one of my own new rules.

SqlCommand sqlCm = null;

public Form1()

{

InitializeComponent();

}

private void btnAsync_Click(object sender, EventArgs e)

{

string strCn = "Data Source=localhost;database=......;User Id=......;PassWord=.......;Async=true;"; //Aync=true is very important.

string strSql = "insert into tblSystemSettings (Value, Setting) values ('Async Test', 'True')";

SqlConnection sqlCn = new SqlConnection(strCn);

sqlCm = new SqlCommand(strSql, sqlCn);

sqlCm.CommandType = CommandType.Text;

sqlCn.Open();

sqlCm.BeginExecuteNonQuery(new AsyncCallback(asyncCallback ), null );

}

public void asyncCallback(IAsyncResult result)

{

sqlCm.EndExecuteNonQuery(result);

// Optionally do some work based on results.

}

No Comments