learn ado.net 2.0 async methods in 60 seconds

5
Learn ADO.NET 2.0 Async Methods in 60 Seconds ©Mohamed ATHIMNI [email protected] 02/2012 – Version 1.0.0 Learn ADO.NET 2.0 Async Methods in 60 Seconds

Upload: code-kernel

Post on 17-Jul-2015

1.331 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Learn ADO.NET 2.0 Async Methods in 60 Seconds

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

Page 2: 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

Page 3: 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

Page 4: 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

Page 5: 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