我有一些带有一些数据的数据网格,我正在通过for ...下一个项目循环 在循环内部,我使用来自datagrid的参数调用Web服务 由于速度很快,工作非常耗时,我想让用户可以选择多次调用他想要的服务。 如何在循环内同时调用Web服务?
答案 0 :(得分:0)
有很多方法可以达到你想要的效果,所以这里有一个使用Task类的例子。关键点是在后台线程内迭代底层数据源(只读)。完成后,返回UI线程并更新。
Private Sub BeginAsyncOp(list As IList)
Static cachedSource As CancellationTokenSource
Static cachedId As Long
If ((Not cachedSource Is Nothing) AndAlso (Not cachedSource.IsCancellationRequested)) Then
cachedSource.Cancel()
End If
cachedSource = New CancellationTokenSource
cachedId += 1L
Dim token As CancellationToken = cachedSource.Token
Dim id As Integer = cachedId
Task.Factory.StartNew(
Sub()
Dim result As IList = Nothing
Dim [error] As Exception = Nothing
Dim cancelled As Boolean = False
Try
'Background thread, do not make any UI calls.
For Each item In list
'...
token.ThrowIfCancellationRequested(True)
Next
result = a_updated_list
Catch ex As OperationCanceledException
cancelled = True
Catch ex As ObjectDisposedException
cancelled = True
Catch ex As Exception
[error] = ex
Finally
If (id = cachedId) Then
Me.Invoke(
Sub()
If (((Not Me.IsDisposed) AndAlso (Not Me.Disposing))) Then
'UI thread.
If (Not [error] Is Nothing) Then
'...
ElseIf (Not cancelled) Then
For Each item In result
'...
Next
End If
End If
End Sub)
End If
End Try
End Sub)
End Sub