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

use*_*208 3 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)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ark 7

看起来您正在尝试调用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
)
Run Code Online (Sandbox Code Playgroud)

您需要遍历Values您的ServerList字典的 ,它们的类型是Server。该TSource泛型参数从参数推断,所以你并不需要指定它的方法调用。