in

Dot Net Mafia

Group site for developer blogs dealing with (usually) .NET, SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, and other Microsoft products, as well as some discussion of general programming related concepts.

This Blog

Syndication

Archives

Corey Roth [MVP]

A SharePoint MVP bringing you the latest time saving tips for SharePoint 2013, SharePoint 2010, Office 365, SharePoint Online, MOSS 2007, ASP.NET, LINQ, and Visual Studio 2012.

Asynchronous Callbacks with ADO.NET 2.0

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

2012 dotnetmafia.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems