My first suggestion was to use only the values from the dictionary:
foreach (BusinessObject> value in _dictionnary.Values) { if(value.MustDoJob) { value.DoJob(); } }
With LINQ, this can be even simpler:
foreach (BusinessObject value in _dictionnary.Values.Where(v => v.MustDoJob)) { value.DoJob(); }
This makes it clearer. However, it is unclear what else is actually causing you a problem. How fast do you need to iterate over a dictionary? I expect this to be pretty nippy already ... is there something really wrong with this brute force approach? What effect did it gain 600 ms to iterate over the collection? Is it 600 ms when nothing needs to be done?
One note: you cannot change the contents of a dictionary while it is repeating - be it in this thread or another. This means that you are not adding, deleting, or replacing key / value pairs. This is normal for BusinessObject content to change, but the dictionary relationship between the key and the object cannot change. If you want to minimize the time during which you cannot change the dictionary, you can take a copy of the list of links to objects that require work, and then iterate over them:
foreach (BusinessObject value in _dictionnary.Values .Where(v => v.MustDoJob) .ToList()) { value.DoJob(); }
source share