VB等待一个异步呼叫,也等待一个呼叫

时间:2019-05-28 21:11:05

标签: vb.net asynchronous async-await

我是VB的新手,对异步功能不是很熟悉。 我需要修复现有代码中的一个错误,该错误中的某些代码在数据加载完成之前正在构建报告。

问题在于在调用loadOption1(data)之前已调用BuildReport()。我需要应用程序在运行之前等待所有LoadAsync()完成,但是当它等待GetData()时,应用程序将返回到start()并过早运行BuildReport()。

代码大致如下:

Public Async Sub start()

    await LoadAsync()

    BuildReport() ' this must not run until everything in Load is complete

End Sub

Public Async Function LoadAsync() As System.Threading.Tasks.Task        
'this is called from other locations, not just from Start()

    dim data = await GetData() 'call to database
    ' at this point start() continues to run
    ' but we need it to keep waiting for these next calls to complete

    'these calls are synchronous, builds objects needed for the report 
    loadOption1(data)
    loadOption2(data)
    loadOption3(data)

    'now we want to return to start()
End Function


Public Async Function GetData(s As Scenario) As Task(Of DataResults)

    ...

    Dim resp = Await Task.Run(Function() ConfigWebService.FetchIncentives(req)) ' soap call

End Function

(每个功能在同一项目中的不同类中)

我尝试从启动功能中删除等待;在BuildReport()被调用后,选项会加载。

如果我从GetData()调用中删除等待,将data.result传递给loadoptions函数,则整个应用程序将永远挂起。

我很困惑。任何提示将不胜感激!

编辑:更新了示例以正确反映实际代码

更新: 我已经尝试了所有我能想到的一切,从.ContinueWith(False)到附加到父任务,再到使用.ContinueWith(),但是到目前为止没有任何效果。 一旦代码在LoadAsync()内部达到等待状态,Start()中的任务即被视为完成

1 个答案:

答案 0 :(得分:0)

似乎唯一起作用的是制作一个isLoading标志,该标志在LoadAsync()开始时设置为true,然后在LoadOptions3()完成后设置为false。然后检查标志的值是否在循环中有延迟更改

Public Async Sub start()

    await LoadAsync()

    For i As Integer = 1 To 50
        If Not IsLoading Then Exit For
        Await System.Threading.Tasks.Task.Delay(100)
    Next

    BuildReport() 

End Sub