C#C
C#3y ago
SWEETPONY

✅ How to improve Parallel.ForEachAsync usage?

private async Task<ConcurrentDictionary<string, string>> GetIpAddresses( HashSet<string> deviceIds )     
{
    var devicesIpAddresses = new ConcurrentDictionary<string, string>();
                                                                                                         
    await Parallel.ForEachAsync(deviceIds, async (deviceId, _) => 
    {
        var archiveQuery = await _archiveClient
            .Query( new QueryArguments
            {
                DeviceIDs = new HashSet<string> {deviceId},
                Order = OrderType.Desc,
                EventNames = new() {"nc100k:connected", "nc60k:connected", "nc8k:connected"},
                Pagination = new() {PageSize = 1} 
            } )                                                                                          
            .Unwrap();                                                                                   
                                                                                                         
        var ip = archiveQuery.Items
            .Select(verbalizedEvent => verbalizedEvent.Items
                .FirstOrDefault(item => item.Type == "endpoint" )?.Title)                              
            .FirstOrDefault() ?? "";                                                                     
                                                                                                         
        devicesIpAddresses[deviceId] = ip;                                                             
    } );                                                                                                 
                                                                                                         
    return devicesIpAddresses;                                                                           
}   
Was this page helpful?