Alright, I am a little late today on the Tip of the Day because I have been absorbed in use cases, but here it is none the less. Although, asynchronous (I'll misspell that word at least two or three times in this article) calls are nothing new to .NET, they have been added to ADO.NET 2.0. Asynchronous callbacks in ADO.NET work just like any other asynchronous call. You start by initializing your connection and SqlCommand just like you would with a normal ADO.NET call. The difference is that you assign an IAsyncResult using the BeginExecuteReader method (in the case of a SqlDataReader). You pass as a parameter to that method the name of the method that will catch the response of the asynchronous call. Lastly, that method will assign a SqlDataReader to the result of the EndExecuteReader method. After that you use the SqlDataReader just as you normally would.
Here is what the code would look like
// declare a command at the class wide level
SqlCommand mySqlCommand;
// start the async process
protected void StartCommand
{
SqlConnection myConnection = new SqlConnection(connectionString);
// open the connection
myConnection.Open();
// create the command
sqlCommand = new SqlCommand("spDoSomething");
// get an IAsyncResult and set the return method to EndCommand
IAsyncResult asynchronousResult = sqlCommand.BeginExecuteReader(EndCommand);
}
// catch the completion of the command
protected void EndCommand(IAsyncResult asynchronousResult)
{
// get a datareader from the result
SqlDataReader sqlDataReader = sqlCommand.EndExecuteReader(asynchronousResult);
// do something with the data reader
}
Of course, you can do this with other types of ADO.NET types (i.e.: SqlDataAdapter, etc.) not just with a SqlDataReader.
Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=164