Parallel.ForEach本地存储

时间:2010-08-03 14:54:01

标签: vb.net parallel-processing

我最近将For Each循环更改为Parallel.ForEach循环。我担心在循环外声明一个对象,但在循环中迭代时分配。这是简化的代码。

Dim results As ModelResults
Dim noResultsModel As New List(Of ModelResults)
Dim lock As New Object
Parallel.ForEach(_modelEngines,
    Sub(model)

    results = model.Execute

    If results IsNot Nothing Then

        SyncLock lock
            noResultsModel.Add(results)
        End SyncLock

    End If

    results = Nothing

End Sub)

结果对象是否存在潜在的竞争条件?如果我将结果声明移到for循环中会有什么不同吗?

1 个答案:

答案 0 :(得分:4)

是的,在循环外声明的变量确实存在竞争条件:

Thread 1: results = model.Execute ' results are from Thread1's current modelEngine
Thread 2: results = model.Execute ' results are from Thread2's current modelEngine
Thread 2: If results IsNot Nothing Then ' results are from Thread2's current modelEngine
Thread 1: If results IsNot Nothing Then ' results are from Thread2's current modelEngine(!)

将它移到里面,我不明白你为什么要在循环之外声明它。