Jyina Jyina - 6 months ago 40
Vb.net Question

How to make a task wait on WCF async callback function?

I have WCF async begin end pattern to call a service function. I have the begin function wrapped inside a task. When task is awaited, it does not wait for the callback function to finish that is passed to the begin function. How can I make it wait for the callback function to finish executing? Thank you.

Here is what I have.

Public Sub Process(pCase)
Dim client As CaseRecord.CaseRecordPort
client = New CaseRecord.CaseRecordPortClient
DirectCast(client, CaseRecord.CaseRecordPortClient).Open()

Dim clientTask As Task = Task.Factory.StartNew(Sub()
client.BeginCaseProcess(pCase, AddressOf CaseRequestCompleted, client)
End Sub)


If IsPaid() Then

End If
End Sub

Private Sub CaseRequestCompleted(ByVal result As IAsyncResult)
Dim client As CaseRecord.CaseRecordPortClient = DirectCast(result.AsyncState, CaseRecord.CaseRecordPortClient)
Dim tCaseResponse As CaseResponse = Nothing
Dim sError As String = ""

tCaseResponse = client.EndCaseProcess(result)
Catch ex As TimeoutException
sError = "Timeout error"
Catch ex As Exception
sError = ex.Message
RaiseEvent CaseRequestCompleted(tCaseResponse, sError)
End Try
End Sub


StartNew is a dangerous API and should not be used. In your case, you don't even need it anyway.

Instead, of calling Begin*/End* explicitly, you can use Task.Factory.FromAsync to wrap them up. My VB is rusty, but the C# code would look like:

CaseResponse tCaseResponse = await Task.Factory.FromAsync(client.BeginCaseProcess,
    clientEndCaseProcess, pCase, null);

For more information, see TAP wrappers for APM.