2014-08-31 66 views
0

我有datagrid与一些数据,我正在循环通过项目与...下一个 在循环内我打电话给Web服务与参数从数据网格 由于速度,工作非常耗时,我想让用户选择多少次多次拨打他想要的服务。 如何在循环内同时调用Web服务?VB.Net线程建议

+0

你现在怎么打你的电话?同样的方式,但每个线程内。您可能需要每次创建一个新频道。另一件事 - 不要从数据网格发送数据,从维护的角度来看,这是低效的。使用基础数据源,如数据表或其后代类。然后你可以拥有强大的类型成员,不需要投射,也不会出错。 – Neolisk 2014-08-31 11:52:58

+0

这种情况很少发生,网络服务会对客户占用资源采取反制措施。他们一次只能处理一个请求,或者将您置于黑名单中,因此您无法再使用该服务。与服务提供商合作寻找更好的解决方案。 – 2014-08-31 13:17:30

回答

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 
+0

我不明白你的观点 – 2014-08-31 19:58:19