0

我有一个程序,它从网站检索数据,即首先它获取类别和子类别并将其存储在类别表中。然后点击相应的类别 URL 并检索产品。

我有一个遍历类别 URL 的外循环和一个处理分页的内循环,还有一个用于检索产品的内循环。

这是我的代码

For item As Integer = 0 To tempTable.Rows.Count - 1
'main loop

     For cycleCount As Integer = -1 To pageNodes.Count - 1
      'pagination loop

       For Each product As HtmlNode In products
         'retrive products here 
       Next


     Next

Next

通常,我的代码工作正常。但我想应用多线程。因此,我在主循环中使用了 TPL(任务并行库)。

IE

Parallel.For(0, tempTable.Rows.Count - 1, Sub(item)
'main loop

     For cycleCount As Integer = -1 To pageNodes.Count - 1
      'pagination loop

       For Each product As HtmlNode In products
         'retrive products here 
       Next


     Next

End Sub)

仅插入了 2 到 4 条记录,但有重复的项目,并且在该代码崩溃之后出现此错误:“发生了一个或多个错误”

那么,如何在我的代码中实现多线程?

4

1 回答 1

0

你用Parallel.For错了。如果您阅读了配置的预期参数(写入Parallel.For(并等待弹出窗口),您会看到第二个参数是toExclusive. 因此,要模仿For item As Integer = 0 To tempTable.Rows.Count - 1你必须写Parallel.For(0, tempTable.Rows.Count, Sub(item). 如果你改变它,你的代码应该可以正常工作。

- 更新

带有易于跟踪的数组的代码示例,表明建议的转换允许您的代码正常工作。

Dim resultString As String = ""
Dim products(2) As Integer
products(0) = 1
products(1) = 2
For item As Integer = 0 To 1
    'main loop
    For cycleCount As Integer = 0 To 1
        'pagination loop

        For Each product As Integer In products
            'retrive products here
            resultString = resultString & "-" & product.ToString()
        Next
    Next
Next

Dim resultString2 As String = ""
Parallel.For(0, 2, Sub(item)
                       'main loop

                       For cycleCount As Integer = 0 To 1
                           'pagination loop

                           For Each product As Integer In products
                               'retrive products here 
                               resultString2 = resultString2 & "-" & product.ToString()
                           Next

                       Next

                   End Sub)

您可以比较两者resultStringresultString2确认两个变量输出完全相同的值,从而正确转换循环。

于 2013-08-06T10:15:50.287 回答