在 VB.NET 中正确使用 async/await?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18750551/
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 15:02:45  来源:igfitidea点击:

Correct use of async/await in VB.NET?

.netvb.netasynchronous

提问by Cuthbert

The following code won't compile with the error: Value of type 'System.Threading.Tasks.Task(Of System.Data.DataTable)' cannot be converted to 'System.Data.DataTable

以下代码不会编译并出现错误: Value of type 'System.Threading.Tasks.Task(Of System.Data.DataTable)' cannot be converted to 'System.Data.DataTable

Private m_country_dt As DataTable = getCountriesAsync()


Private Async Function getCountriesAsync() As Task(Of DataTable)
    Dim dt As DataTable = Await Task(Of DataTable).Factory.StartNew(Function() getCountries_dt())

    Return dt
End Function

Private Function getCountries_dt() As DataTable
    Dim sp As New dbCore.StoredProcedure
    Return sp.GetAllCountries()
End Function

Can someone tell me what I might be doing wrong here? GetAllCountriesis a function that queries a SQL database for.. all the countries in it and returns this in a DataTable. This code is located inside of a Module.

有人可以告诉我我在这里可能做错了什么吗?GetAllCountries是一个查询 SQL 数据库中所有国家/地区的函数,并以DataTable. 此代码位于模块内部。

回答by Stephen Cleary

You have to Awaitit to unwrap the Task (Of DataTable).

你必须用Await它来解开Task (Of DataTable).

On a side note, you should prefer Task.Runover Task.Factory.StartNew(I describe why on my blog). Though in this case, I would try to use the ADO.NET async methods instead of just running the synchronous methods on a background task.

在一个侧面说明,你应该更喜欢Task.RunTask.Factory.StartNew(我说明为什么在我的博客)。尽管在这种情况下,我会尝试使用 ADO.NET 异步方法,而不是仅在后台任务上运行同步方法。