- * There might be some threads out that could be about to execute stuff from the given domain.
- * We avoid that by setting up a semaphore to be pulsed by the thread that reaches zero.
- */
- sem = domain->cleanup_semaphore = CreateSemaphore (NULL, 0, 1, NULL);
+ * There might be some threads out that could be about to execute stuff from the given domain.
+ * We avoid that by waiting on a semaphore to be pulsed by the thread that reaches zero.
+ * The semaphore is only created for domains which queued threadpool jobs.
+ * We always wait on the semaphore rather than ensuring domain->threadpool_jobs is 0.
+ * There may be pending outstanding requests which will create new jobs.
+ * The semaphore is signaled the threadpool domain has been removed from list
+ * and we know no more jobs for the domain will be processed.
+ */
+
+ mono_lazy_initialize(&status, initialize);
+ mono_coop_mutex_lock(&threadpool->domains_lock);
+
+ tpdomain = domain_get (domain, FALSE);
+ if (!tpdomain || tpdomain->outstanding_request == 0) {
+ mono_coop_mutex_unlock(&threadpool->domains_lock);
+ return TRUE;
+ }