The asynchronous operation has already completed.

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
I have a DataGridView which uses SqlNotificationRequests to update when changes are made to the underlying data in SQL. This is working fine (after following this article: http://msdn.microsoft.com/en-US/library/3ht3391b(v=vs.80).aspx http://msdn.microsoft.com/en-US/library/3ht3391b(v=vs.80).aspx )
but every now and again I get an error:
Message: The asynchronous operation has already completed.
Stack Trace: at System.Data.SqlClient.SqlCommand.VerifyEndExecuteState(DbAsyncResult dbAsyncResult, String endMethod)
at System.Data.SqlClient.SqlCommand.InternalEndExecuteReader(IAsyncResult asyncResult, String endMethod)
at System.Data.SqlClient.SqlCommand.EndExecuteReader(IAsyncResult asyncResult)

<pre class="prettyprint lang-vb Private Sub OnTransfersReaderComplete(ByVal asynResult As IAsyncResult)
myStatus.addHistory("OnTransferReaderComplete", "Sub")

You may not interact with the form and its contents
from a different thread, and this callback procedure
is all but guaranteed to be running from a different thread
than the form. Therefore you cannot simply call code that
updates the UI.
Instead, you must call the procedure from the forms thread.
This code will use recursion to switch from the thread pool
to the UI thread.
If Me.InvokeRequired Then
Dim switchThreads As New AsyncCallback(AddressOf Me.OnTransfersReaderComplete)
Dim args() As Object = {asynResult}
Me.BeginInvoke(switchThreads, args)
Exit Sub
End If

At this point, this code will run on the UI thread.
Try
waitInProgressTransfers = False
Dim messageBody As New List(Of SqlBytes)
Trace.WriteLine(String.Format("Transfer:asynResult.IsCompleted1: {0}", asynResult.IsCompleted.ToString), "SqlNotificationRequest")
Dim reader As SqlDataReader = DirectCast(asynResult.AsyncState, SqlCommand).EndExecuteReader(asynResult)
Trace.WriteLine(String.Format("Transfer:asynResult.IsCompleted2: {0}", asynResult.IsCompleted.ToString), "SqlNotificationRequest")
Do While reader.Read
Empty queue of messages.
Application logic could parse
the queue data to determine why things.
For i As Integer = 0 To reader.FieldCount - 1
Debug.WriteLine(reader(i).ToString())
Console.WriteLine(reader(i).ToString)
Next

messageBody.Add(reader.GetSqlBytes(reader.GetOrdinal("message_body")))

Dim bytesQN As SqlBytes = reader.GetSqlBytes(reader.GetOrdinal("message_body"))
Loop

reader.Close()
Catch ex As Exception
Call errorHandling(ex, "OnTransfersReaderComplete", "Sub")
End Try
End Sub[/code]
There is more to the Sub above where it handles the returned data and starts a new SqlNotificationRequest but the above error appears when the EndExecuteReader is called. When I trace the status of the asynResult object, it shows that it is completed
before I call the EndExecuteReader whether or not the error occurs.<br/>



View the full article
 
Back
Top