Fix multi-threading issues.

This pull request addresses domain and concurrency issues by implementing additional locks and error checking. The modifications are based on the pull request monobjc#405.