并行运行.Net任务,返回不同的对象

时间:2013-09-10 14:05:51

标签: vb.net task-parallel-library .net-4.5 async-await

我目前正在寻找处理来自WCF服务的2个数据下载,这些服务返回不同对象的集合,并且想知道是否有比同步运行两个异步任务更好的方法。

在这种情况下,我可以实现Task.WhenAllTask.WhenAny方法来并行运行这些任务吗?

Public Property Users As IEnumerable(Of UserDto)
    Get
        Return _users
    End Get
    Set(value As IEnumerable(Of UserDto))
        _users = value
        RaisePropertyChanged("Users")
    End Set
End Property

Public Property ApplicationRoles() As IEnumerable(Of ApplicationRoleDto)
    Get
        Return _roles
    End Get
    Set(ByVal value As IEnumerable(Of ApplicationRoleDto))
        _roles = value
        RaisePropertyChanged("ApplicationRoles")
    End Set
End Property

Private Async Sub GetUserDetails()
    Users = Await _serviceHelper.GetUsers()
    ApplicationRoles = Await _serviceHelper.GetApplicationRoles
End Sub

可能的解决方案

我可以使用Task Parrallel Library,但我不确定这是否是最有效的方法,而且我无法等待返回。

Parallel.Invoke(Sub() Users = _serviceHelper.GetUsers(),
                    Sub() ApplicationRoles = _serviceHelper.GetApplicationRoles())

1 个答案:

答案 0 :(得分:1)

Task.WhenAll应该可以正常工作。请原谅,如果语法不正确;我的VB非常生疏:

Private Async Function GetUserDetailsAsync() As Task
  Dim UsersTask = _serviceHelper.GetUsersAsync()
  Dim ApplicationRolesTask = _serviceHelper.GetApplicationRolesAsync
  Await Task.WhenAll(UsersTask, ApplicationRolesTask);
  Users = Await UsersTask
  ApplicationRoles = Await ApplicationRolesTask
End Function

我也冒昧地将您的Sub更改为Function(您应该避免Async Sub),并使Async方法以Async结尾,as per the convention