如何使用参数制作简单的异步包装器

时间:2012-07-31 06:03:14

标签: .net vb.net visual-studio-2012 async-await

我想将现有的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等价物中而不重构原始的?

1 个答案:

答案 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:不要这样做,只会让您的用户感到困惑,如果他们需要,他们也可以自己动手。