Adding locks around some collection loops

* Issue #510 - dictionary changed size during iteration