ADO.NET Async command no-no number 1

I was working on some asynchronous commands in ADO.NET Whidbey on Sunday.  I was trying to see the amount of time that might elapse between a command starting to execute and the time that the server operation actually occurs.  I did something like the code listed below.  Note: that this is not the specific code.

iResult = sqlCm.BeginExecuteNonQuery(New System.AsyncCallback(AddressOf ExecuteNonQueryCallback), sqlCm)

While Not iResult.IsCompleted

End While

....................

Private Sub ExecuteNonQueryCallback(ByVal iRes As IAsyncResult)

      Dim sqlCm As SqlCommand = CType(iRes.AsyncState, SqlCommand)

      sqlCm.EndExecuteNonQuery(iRes)

End Sub

So, why is this code bad?  Well, the loop where I am checking for the result to see if things are completed is kind of a bad idea.  The CPU will literally begin spinning waiting on this operation to happen.  This is a bad thing as the calling seems to take over the CPU and Callback method, which should be called signalling that the command has been completed,  may not ever get run and the result is that you are stuck in the loop.  Bottom line, don't loop thru waiting on the response to end.  If you do, strange things happen.

So, why did I do this?  Well, I was playing with the async ADO.NET commands and I wanted to experiment.  I thought this would be cool to try.  Not thinking about this too much, I had several brain farts trying to figure out I was going into a loop and never ending.  I tried calling Thread.Sleep() and Application.DoEvents with not luck from within the loop.

Wally

 

2 Comments

  • Do this instead.



    Dim doneEvt As New AutoResetEvent(False)



    iResult = sqlCm.BeginExecuteNonQuery(New System.AsyncCallback(AddressOf ExecuteNonQueryCallback), sqlCm)



    doneEvt.WaitOne()



    ....................



    Private Sub ExecuteNonQueryCallback(ByVal iRes As IAsyncResult)



    Dim sqlCm As SqlCommand = CType(iRes.AsyncState, SqlCommand)



    sqlCm.EndExecuteNonQuery(iRes)

    doneEvt.Set()

    End Sub



    Don't forget to include System.Threading namespace.

  • Good suggestion.



    Wally

Comments have been disabled for this content.