我想将现有的Forms项目带到VS2012 RC,并为一些长程序添加一些快速的Async / Await包装器。我想在Async
等价物中包装现有过程而不更改原件。
到目前为止,我已经取得了这样的成功:
'old synchronous function:
Public Function UpdateEverything() As Boolean
'Do lots of predictable updates
...
Return True
End Function
'new asynchronous wrapper:
Public Async Function UpdateEverythingAsync() As Task(Of Boolean)
Return Await Task.Run(AddressOf Me.UpdateEverything)
End Function
但这只有效,因为UpdateEverything
没有参数。如果原始函数有任何参数,我无法计算出语法。例如,如果我有:
'old synchronous function:
Public Function UpdateSomething(somethingID As Integer) As Boolean
'Do updates
...
Return True
End Function
我以为会:
Public Async Function UpdateSomethingAsync(somethingID As Integer) As Task(Of Boolean)
Return Await Task.Run(Of Boolean)(New Func(Of Integer, Boolean)(AddressOf Me.UpdateSomething))
End Function
但显然并非那么简单。有没有一种简单的方法可以将它包装在Async等价物中而不重构原始的?
答案 0 :(得分:2)
Public Async Function UpdateSomethingAsync(somethingID As Integer) As Task(Of Boolean)
Return Await Task.Run(Of Boolean)(New Func(Of Integer, Boolean)(AddressOf Me.UpdateSomething))
End Function
这个方法有些奇怪:你期望UpdateSomething()
方法接收somethingID
参数,但你永远不会将它传递给它。您不能在此处直接使用UpdateSomething
作为委托,但您可以使用lambda:
Public Async Function UpdateSomethingAsync(somethingID As Integer) As Task(Of Boolean)
Return Await Task.Run(Of Boolean)(Function() (UpdateSomething(somethingID)))
End Function
虽然您在此处不需要Async
,但您可以直接返回Task
来提高方法效率:
Public Function UpdateSomethingAsync(somethingID As Integer) As Task(Of Boolean)
Return Task.Run(Of Boolean)(Function() (UpdateSomething(somethingID)))
End Function
话虽如此,我同意the Stephen Toub article I linked before:不要这样做,只会让您的用户感到困惑,如果他们需要,他们也可以自己动手。