Execute an asynchronous query
Some ADO.NET classes supports built-in asynchronous query behavior. Some aren’t. In this post, we’ll revise the former classes, like SqlDataReader. However, if you are familiar with multithread computing (particularly, in the .NET Framework) you can easily implement asynchronous execution in classes which don’t support it, such as the TableAdapter.
Before you’d do anything, you should introduce a new name-value pair into your connection string: Async=true or Asynchronous Processing=true. Including it, you enable asynchronous queries to be executed on the database server. This was the easy part.
Writing your asynchronous data access class is a little bit more complicated. If you are familiar with delegates and the classes of System.Threading, then you are ready to go. But if you’d like to rely on built-in logic, consider using the DbCommand’s BeginExecuteReader and EndExecuteReader. First the code, then the explanation:
SqlConnection theConnection = new SqlConnection(“connectionString”);
SqlCommand theCommand = new SqlCommand(“command”, theConnection);
IAsyncResult theResult = theCommand.BeginExecuteReader(new AsyncCallback(DataComplete), theCommand);
public static void DataComplete(IAsyncResult result)
SqlCommand theCommand = (SqlCommand)result.AsyncState;
SqlDataReader theReader = theCommand.EndExecuteReader(result);
//Deal with the results.
As you can see, we’ve created an IAsyncResult object by using the DbCommand.BeginExecuteReader method, passed a callback method and the command itself as parameters. Then we’ve created the method, which accepts the IAsyncResult object. Because we passed the command object as the state object, we are able to retrieve it by casting the IAsyncResult.AsyncState property into a SqlCommand. Then we call the EndExecuteReader method of the command, passing the IAsyncResult object as parameter, and building our DataReader with the help of it. Then we’re ready to iterate over the returned data.
I'm a software developer professionalizing in the .NET platform and iOs development. Here you can find my notes for Microsoft certifications.
Everyone who seeks, finds
- .NET (35)
- .NET 70-536 (35)
- Configuration, Diagnostic, Management and Installation Features (6)
- Globalization, Drawing and Text Manipulation (2)
- Improving the Security of a .NET Framework Application (5)
- Interoperability, Reflection and Mailing Functionality (3)
- Serialization and IO Functionality (7)
- Service Processes, Threading and Application Domains (2)
- System Types and Collections (6)
- .NET 70-536 (35)
- ADO.NET (24)
- ASP.NET (68)
- Application Architecture (1)
- ASP.NET 70-562 (44)
- PRO ASP.NET 70-564 (20)
- Design Patterns (10)
- Objective-C (4)
- Personal (4)
- Silverlight (6)
- SQL Server (43)
- 70-433 (27)
- 70-451 (16)
- WCF (8)
- Windows Azure (8)
- WPF (20)