在VB中正确使用Async / Await

时间:2016-12-09 16:37:18

标签: vb.net asynchronous

我无法使用Async / Await从WCF服务获取数据表并将其加载到datagridview中。这是我第一次这样做,我觉得我错过了一些基本的东西。这是我到目前为止的代码:

Private p_oDataService As New SQLService.DataServiceClient

Async Function GetReportDataTable() As Task(Of DataTable)
  Try
    p_oDataService = New SQLService.DataServiceClient
    Dim tDatatable As Task(Of DataTable) = p_oDataService.GetValidationReportsAsync()
    Dim dt As DataTable = Await tDatatable
    Return dt
  Catch ex As Exception
    Throw ex
  End Try
End Function 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Try
    Dim tDT As Task(Of DataTable) = GetReportDataTable()
    Dim dt As DataTable = GetReportDataTable.Result
    DataGridView1.AutoGenerateColumns = True
    DataGridView1.DataSource = dt
  Catch ex As Exception
    Throw ex
  End Try
End Sub

感谢任何帮助!

1 个答案:

答案 0 :(得分:4)

您正在混合阻止和异步调用。当你致电GetReportDataTable.Result时,它会陷入僵局。

事件处理程序允许您等待异步任务,因此更新事件处理程序...

Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Try
      Dim dt As DataTable = Await GetReportDataTable()
      DataGridView1.AutoGenerateColumns = True
      DataGridView1.DataSource = dt
    Catch ex As Exception
      Throw ex
    End Try
End Sub