Fix multi-domain and multi-threading issues.

This commit addresses domain and concurrency issues by implementing additional locks, error checking, and cross-domain marshaling.