0

我目前正在研究处理来自 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

可能的解决方案

我可以使用任务并行库,但我不确定这是否是最有效的方法,而且我不能等待返回。

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

1 回答 1

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为 a Function(您应该避免Async Sub),并按照约定使您的方法Async结尾。Async

于 2013-09-10T14:37:30.463 回答