【发布时间】:2014-05-30 04:13:40
【问题描述】:
我的团队第一次使用任务并行库,我的同事想出了一些代码,如下所示。我们正在运行一些东西,然后使用该数据发出进一步的服务器请求(名称中带有Async 的方法),然后使用从该服务器调用返回的数据来获取更多数据。加载完所有这些后,UI 上的一些项目(通常是组合框)会更新(在名称中带有 Returned 的方法中),用户可以将其用于过滤器。
基本上,我们确定用户可以访问哪些公司,然后根据该信息,我们为数据加载更多“过滤器”(加载一些默认值),然后从默认视图加载数据。
虽然代码有效,但似乎有很多重复的代码,我想知道是否可以使用扩展方法或其他代码更改来减少执行此类操作所需的代码量。
Private Sub GetAndLoadViewData()
Dim noCancelToken = CancellationToken.None
Const attachToParent As TaskContinuationOptions = TaskContinuationOptions.AttachedToParent
Task.Factory.StartNew(
Sub()
'fire off child tasks
Task.Factory.StartNew(Function() GetCompaniesAsync()).ContinueWith(
Sub(t As Task(Of List(Of Company))) CompaniesReturned(t), noCancelToken, attachToParent, UiSyncContext)
Task.Factory.StartNew(Function() GetUserAsync()).ContinueWith(
Sub(t As Task(Of User)) UserReturned(t), noCancelToken, attachToParent, UiSyncContext)
End Sub).ContinueWith(
Sub(prevTask)
'these tasks depend on the success of the previous task
If Not prevTask.IsFaulted Then
Task.Factory.StartNew(Function() GetFiltersAsync()).ContinueWith(
Sub(t As Task(Of List(Of Filter))) FiltersReturned(t), noCancelToken, attachToParent, UiSyncContext)
Else
'Rethrow the exception from the previous task if an exception occurred
Throw prevTask.Exception
End If
End Sub).ContinueWith(
Sub(prevTask)
'these tasks depend on the success of the previous task
If Not prevTask.IsFaulted Then
Task.Factory.StartNew(Function() GetDataAsync(CurrentCompany, CurrentFilters)).ContinueWith(
Sub(t As Task(Of List(Of Data))) DataReturned(t), noCancelToken, attachToParent, UiSyncContext)
Else
'Rethrow the exception from the previous task if an exception occurred
Throw prevTask.Exception
End If
End Sub).ContinueWith(
Sub(prevTask)
If prevTask.IsFaulted Then
View.HandleFatalException(prevTask.Exception.InnerExceptions.First())
Else
View.DisplayData()
End If
End Sub, UiSyncContext)
End Sub
我会注意到,由于业务原因,我们目前只能使用 .NET Framework 4.0。
如果需要更多信息,请告诉我。
【问题讨论】:
标签: .net vb.net task-parallel-library