viernes, 30 de mayo de 2008

Operaciones de Acceso a datos Asincronico

Se han fijado que en los commands tiene nuevos metodos que son parecidos a los que ya conoces pero tienen la palabra Begin ante puesta, como por ejemplo el ExecuteReader tiene
BeginExecuteReader y EndExecuteReader estos son metodos del modelo asincronico, aqui un ejemplo de como utilizarlos.
Solo recuerde que para utilizar sincronia necesita poner la siguiente clausula en el connetion string:
Asynchronous Processing=true

Dim cnstring As String = "user id=sa;" & _
"password=pass;initial catalog=northwind;" & _
" data source=.\sqlexpress;Asynchronous Processing=true"


Dim cn1 As New SqlClient.SqlConnection(cnstring)
Dim cn2 As New SqlClient.SqlConnection(cnstring)
Dim cn3 As New SqlClient.SqlConnection(cnstring)


Dim commandText1 As String = _
"WAITFOR DELAY '0:0:01';" & _
"SELECT * FROM products " & _
" WHERE PRODUCTID=50"


Dim commandText2 As String = _
"WAITFOR DELAY '0:0:05';" & _
"SELECT * FROM products " & _
" WHERE PRODUCTID=50"


Dim commandText3 As String = _
"WAITFOR DELAY '0:0:10';" & _
"SELECT * FROM products " & _
" WHERE PRODUCTID=50"


Dim waitHandles(2) As Threading.WaitHandle
Try
cn1.Open()
Dim command1 As New SqlClient.SqlCommand(commandText1, cn1)
Dim result1 As IAsyncResult = command1.BeginExecuteReader()
waitHandles(0) = result1.AsyncWaitHandle


cn2.Open()
Dim command2 As New SqlClient.SqlCommand(commandText2, cn2)
Dim result2 As IAsyncResult = command2.BeginExecuteReader()
waitHandles(1) = result2.AsyncWaitHandle


cn3.Open()
Dim command3 As New SqlClient.SqlCommand(commandText3, cn3)
Dim result3 As IAsyncResult = command3.BeginExecuteReader()
waitHandles(2) = result3.AsyncWaitHandle


Dim index As Integer
For countWaits As Integer = 1 To 3
index = Threading.WaitHandle.WaitAny(waitHandles, 60000, False)
Select index
Case 0
     Dim reader1 As SqlClient.SqlDataReader
     reader1 = command1.EndExecuteReader(result1)
    If reader1.Read Then
          TextBox1.Text = "Terminado 1 - " & _
          System.DateTime.Now.ToLongTimeString()
    End If
    reader1.Close()

Case 1
     Dim reader2 As SqlClient.SqlDataReader
     reader2 = command2.EndExecuteReader(result2)
     If reader2.Read Then
            TextBox2.Text = "Terminado 2 - " & _
            System.DateTime.Now.ToLongTimeString()
     End If
   reader2.Close()
Case 2
     Dim reader3 As SqlClient.SqlDataReader
     reader3 = command3.EndExecuteReader(result3)
    If reader3.Read Then
        TextBox3.Text = "Terminado 3 - " & _
        System.DateTime.Now.ToLongTimeString()
    End If
    reader3.Close()
 Case Threading.WaitHandle.WaitTimeout
      Throw New TimeoutException("Timeout")
 End Select

  Next
Catch ex As Exception
     TextBox4.Text = ex.ToString
End Try

1 comentario:

Anónimo dijo...
Este blog ha sido eliminado por un administrador de blog.