'Parallel.Foreach on values (Concurrent Bag) of one key in Concurrent Dictionary
I am having problems converting a ForEach loop into a Parallel.ForEach loop.
I have a Concurrent Dictionary:
private readonly ConcurrentDictionary<string, ConcurrentBag<ParentClass>> ObjectDict = new();
which contains:
- as key:
stringof object "type" - as value: a ConcurrentBag of objects of a class which inherited from
ParentClass. In the following code it shall beObjectA.
Object A inherits from ParentClass.
My goal is to cycle through the Concurrent Bag of one Key-Entry in the Concurrent Dictionary.
Now I am struggling to convert the following ForEach Loop to Parallel.ForEach
foreach (ObjectA objA in ObjectDict["Object A"])
{
objA.ObjectASpecificMethod();
}
To
Parallel.ForEach(ObjectDict["Object A"], objA =>
{
objA.ObjectASpecificMethod();
}
The problem is that objA is not of type ObjectA but of ParentClass as defined in the Concurrent Dictionary ObjectDict. But ParentClass does not have the Childclass specific Method.
I hope I could clarify myself properly.
Solution 1:[1]
You can specify the type, just as you can do in your regular foreach:
Parallel.ForEach(ObjectDict["Object A"], (ObjectsA objectA) =>
{
objectA.ObjectASpecificMethod();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nvoigt |
