如何使任务等待WCF异步回调函数?

时间:2016-08-08 20:01:35

标签: .net vb.net wcf task-parallel-library

我有WCF异步开始结束模式来调用服务功能。我把begin函数包装在一个任务中。当等待任务时,它不会等待回传函数完成传递给begin函数。如何让它等待回调函数完成执行?谢谢。

这就是我所拥有的。

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)

    clientTask.Wait()

     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 = ""

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

1 个答案:

答案 0 :(得分:1)

StartNew是一种危险的API,不应使用。在你的情况下,你甚至不需要它。

而是明确调用Begin* / End*,您可以使用Task.Factory.FromAsync来包装它们。我的VB生锈了,但C#代码看起来像:

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

有关详细信息,请参阅TAP wrappers for APM