使用VB.Net Parallel.ForEach和ConcurrentDictionary的正确语法是什么?

时间:2015-01-29 23:26:11

标签: vb.net parallel-processing parallel.foreach

使用Parallel.ForEach和ConcurrentDictionary我很难获得正确的语法。下面的Parallel.ForEach的正确语法是什么?

Dim ServerList as New ConcurrentDictionary(Of Integer, Server)
Dim NetworkStatusList as New ConcurrentDictionary(Of Integer, NetworkStatus)

... (Fill the ServerList with several Server class objects)

'Determine if each server is online or offline.  Each call takes a while...
Parallel.ForEach(Of Server, ServerList, Sub(myServer)
        Dim myNetworkStatus as NetworkStatus = GetNetworkStatus(myServer)
        NetworkStatusList.TryAdd(myServer.ID, myNetworkStatus)
    End Sub

... (Output the list of server status to the console or whatever)

1 个答案:

答案 0 :(得分:3)

看起来你试图调用Parallel.ForEach(OF TSource)(IEnumerable(Of TSource), Action(Of TSource))重载,在这种情况下我相信你想要这样的东西:

'Determine if each server is online or offline.  Each call takes a while...
Parallel.ForEach(
    ServerList.Values,
    Sub(myServer)
        Dim myNetworkStatus as NetworkStatus = GetNetworkStatus(myServer)
        NetworkStatusList.TryAdd(myServer.ID, myNetworkStatus)
    End Sub
)

您需要迭代Values ServerList字典,Server类型TSource。 {{1}}泛型参数是从参数中推断出来的,因此您无需在方法调用中指定它。