vb.net 在 VB 中正确使用 Async/Await

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41064994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:08:24  来源:igfitidea点击:

Using Async/Await correctly in VB

vb.netasynchronous

提问by cjw

I am having trouble getting a datatable from a WCF service using Async/Await and loading it into a datagridview. This is my first time doing this, I feel like I am missing something basic. This is the code I have so far:

我无法使用 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

Any help is appreciated!

任何帮助表示赞赏!

回答by Nkosi

You are mixing blocking and async calls. When you call GetReportDataTable.Resultit will deadlock.

您正在混合阻塞和异步调用。当你调用GetReportDataTable.Result它时会死锁。

Event handlers allow you to await async tasks as well so update the event handler...

事件处理程序允许您等待异步任务以及更新事件处理程序...

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