Mega Code Archive

 
Categories / VB.Net Tutorial / Database ADO Net
 

Start the process of retrieving a data reader asynchronously

Imports System.Data.SqlClient Module Module1     Sub Main()         Dim commandText As String = _          "WAITFOR DELAY '00:00:03';" & _          "SELECT LastName, FirstName FROM Person.Contact " & _          "WHERE LastName LIKE 'M%'"         RunCommandAsynchronously(commandText, "Data Source=(local);Integrated Security=true;Initial Catalog=AdventureWorks; Asynchronous Processing=true")         Console.WriteLine("Press ENTER to continue.")         Console.ReadLine()     End Sub     Private Sub RunCommandAsynchronously(ByVal commandText As String, ByVal connectionString As String)         Using connection As New SqlConnection(connectionString)            Dim command As New SqlCommand(commandText, connection)            connection.Open()            Dim result As IAsyncResult = command.BeginExecuteReader()            Dim count As Integer            While Not result.IsCompleted                count += 1                Console.WriteLine("Waiting ({0})", count)                Threading.Thread.Sleep(100)            End While            Using reader As SqlDataReader = command.EndExecuteReader(result)                DisplayResults(reader)            End Using         End Using     End Sub     Private Sub DisplayResults(ByVal reader As SqlDataReader)         While reader.Read()             For i As Integer = 0 To reader.FieldCount - 1                 Console.Write("{0} ", reader.GetValue(i))             Next         End While     End Sub End Module