learn ado.net 2.0 async methods in 60 seconds
TRANSCRIPT
Learn ADO.NET 2.0 Async Methods in 60 Seconds
©Mohamed ATHIMNI
[email protected]/2012 – Version 1.0.0
Learn ADO.NET 2.0 Async Methods in 60 Seconds
1. Setting Up Asynchronous Commands• To enable asynchronous commands, you must
set the new Async attribute to true in the connection string.
• If you need both synchronous and asynchronous commands, employ different connections wherever possible.
Learn ADO.NET 2.0 Async Methods in 60 Seconds
2. Nonblocking Commands
• Nonblocking commands are the simplest case of asynchronous commands.
• The code starts the operation and continues executing other unrelated methods.
// Start a non-blocking execution
IAsyncResult iar = cmd.BeginExecuteReader();
// Do something else meanwhile
...
// Block the execution until done
SqlDataReader reader = cmd.EndExecuteReader(iar);
// Process data here ...
ProcessData(reader);
Learn ADO.NET 2.0 Async Methods in 60 Seconds
2. Nonblocking Commands
• As an alternative, the client code might want to check the status of a running asynchronous operation and poll for:
// Executes a query statement
IAsyncResult iar = cmd.BeginExecuteReader();
do
{ // Do something here
} while (!iar.IsCompleted);
// Sync up
SqlDataReader reader = cmd.EndExecuteReader(iar);
ProcessData(reader);
Learn ADO.NET 2.0 Async Methods in 60 Seconds
2. Nonblocking Commands
• The third option for nonblocking commands pass a delegate to a BeginExecuteXXX:
// Begin executing the command
IAsyncResult ar = cmd.BeginExecuteReader( new AsyncCallback(ProcessData), cmd);
public void ProcessData(IAsyncResult iar)
{
// Retrieve the context of the call
SqlCommand cmd = (SqlCommand) iar.AsyncState;
// Complete the async operation
SqlDataReader reader = cmd.EndExecuteReader(ar); ...
}
Learn ADO.NET 2.0 Async Methods in 60 Seconds