【发布时间】:2016-03-21 12:46:10
【问题描述】:
我有一个现有的 dll,其功能可能需要一些时间来检索客户数据。到目前为止,我一直在使用良好的旧 threading.thread.start 方法来防止 UI 锁定,但我一直在尝试了解 .net 4.5 中的 Await/Async 方法。 有没有一种简单的方法可以围绕这些函数创建一个 Await 包装器?我可以将 dll 更新到 4.5,但不能更改代码本身的结构。我尝试的一切都会导致错误.. 'Await 要求 'Boolean' 类型有合适的 GetAwaiter 方法'
示例代码是....
Public Async Function GetByID(id As Integer) As Task(Of Boolean)
'serviceBase is a dll with a number of functions for getting
'data that returns true when a customer object has been filled
Return Await ServiceBase.GetCustomer(id)
End Function
我不明白的是,如果我可以在 ServiceBase 中更新 GetCustomer,那么我必须将其标记为异步并返回一个任务(布尔值)。但是后来我得到了错误,因为 GetCustomer 在任何时候都不需要使用 Await - 它的一些小进程总共加起来是一个被阻止的 UI。
【问题讨论】:
-
获取客户的行为实际上是异步操作吗?制作同步方法
Async毫无意义。你能在 GetCustomer 中显示代码吗,在这种情况下更有趣。 -
该函数的一个示例(例如,客户可能有关于源 A 和 C 的详细信息)' Public Function GetCustomer(id As Integer) As Boolean If GetFromSourceA(id) Then '与客户一起工作并返回 true End If GetFromSourceB(id) Then '与客户合作并返回 true End If GetFromSourceC(id) Then '与客户合作并返回 true End If IsNothing(customer) Then Return False Return True End函数'
-
@kai 的意思是,除非
GetCustomer返回一个任务,否则调用Await GetCustomer不会自动使其异步。async/await是一种语法糖,它使得 awaiting 对于already 异步方法更容易。例如,如果GetCustomer调用Web 服务,您可以使用Await client.CallThatMethodAsync异步调用服务方法并获取结果,而不是同步调用client.CallThatMethod。如果是数据库访问方式,可以使用ExecuteReaderAsync而不是ExecuteReader -
那么我们是说在场景中我最好的方法是像我一样创建一个线程,而 Await 并不适合这种场景?
标签: vb.net async-await