Adding locks around some collection loops

* Issue #510 - dictionary changed size during iteration
Merge pull request #518 from jimi1283/issue_510

Adding locks around some collection loops