- /* When we reach here, the other thread has already exited the critical section, so this is safe to free */
- mono_coop_cond_destroy (&req->cond);
- mono_coop_mutex_destroy (&req->mutex);
- g_free (req);
-#endif
+ if (!ret) {
+ /* Try removing the req from domains_to_finalize:
+ * - if it's not found: the domain is being finalized,
+ * so we the ref count is already decremented
+ * - if it's found: the domain is not yet being finalized,
+ * so we can safely decrement the ref */
+
+ gboolean found;
+
+ mono_finalizer_lock ();
+
+ found = g_slist_index (domains_to_finalize, req) != -1;
+ if (found)
+ domains_to_finalize = g_slist_remove (domains_to_finalize, req);
+
+ mono_finalizer_unlock ();
+
+ if (found) {
+ /* We have to decrement it wherever we
+ * remove it from domains_to_finalize */
+ if (InterlockedDecrement (&req->ref) != 1)
+ g_error ("%s: req->ref should be 1, as we are the first one to decrement it", __func__);
+ }
+
+ goto done;
+ }