[system] Don't throw ObjectDisposedException on cancelled async WebConnection. Fixes...
[mono.git] / mono / metadata / threadpool.c
index f552e17f65c3e5be97a3f70e3007ccdf2a70e713..c901d401acad6bd05f00ea1c750fab9114803b57 100644 (file)
@@ -26,6 +26,7 @@
 #include <mono/metadata/mono-cq.h>
 #include <mono/metadata/mono-wsq.h>
 #include <mono/metadata/mono-ptr-array.h>
+#include <mono/metadata/object-internals.h>
 #include <mono/io-layer/io-layer.h>
 #include <mono/utils/mono-time.h>
 #include <mono/utils/mono-proclib.h>
 #endif
 
 #include "threadpool.h"
+#include "threadpool-ms.h"
+#include "threadpool-ms-io.h"
+
+static gboolean
+use_ms_threadpool (void)
+{
+       static gboolean use_ms_tp = -1;
+       const gchar *mono_threadpool_env;
+       if (use_ms_tp != -1)
+               return use_ms_tp;
+       else if (!(mono_threadpool_env = g_getenv ("MONO_THREADPOOL")))
+               return use_ms_tp = FALSE;
+       else if (strcmp (mono_threadpool_env, "microsoft") == 0)
+               return use_ms_tp = TRUE;
+       else
+               return use_ms_tp = FALSE;
+}
 
 #define THREAD_WANTS_A_BREAK(t) ((t->state & (ThreadState_StopRequested | \
                                                ThreadState_SuspendRequested)) != 0)
 
-#define SMALL_STACK (128 * (sizeof (gpointer) / 4) * 1024)
-
 /* DEBUG: prints tp data every 2s */
 #undef DEBUG 
 
@@ -77,31 +93,14 @@ enum {
        KQUEUE_BACKEND
 };
 
-typedef struct {
-       mono_mutex_t io_lock; /* access to sock_to_state */
-       int inited; // 0 -> not initialized , 1->initializing, 2->initialized, 3->cleaned up
-       MonoGHashTable *sock_to_state;
-
-       gint event_system;
-       gpointer event_data;
-       void (*modify) (gpointer p, int fd, int operation, int events, gboolean is_new);
-       void (*wait) (gpointer sock_data);
-       void (*shutdown) (gpointer event_data);
-} SocketIOData;
+enum {
+       MONITOR_STATE_AWAKE,
+       MONITOR_STATE_FALLING_ASLEEP,
+       MONITOR_STATE_SLEEPING
+};
 
 static SocketIOData socket_io_data;
 
-/* Keep in sync with the System.MonoAsyncCall class which provides GC tracking */
-typedef struct {
-       MonoObject         object;
-       MonoMethodMessage *msg;
-       MonoMethod        *cb_method;
-       MonoDelegate      *cb_target;
-       MonoObject        *state;
-       MonoObject        *res;
-       MonoArray         *out_args;
-} ASyncCall;
-
 typedef struct {
        MonoSemType lock;
        MonoCQ *queue; /* GC root */
@@ -142,20 +141,23 @@ static void threadpool_kill_idle_threads (ThreadPool *tp);
 static gboolean threadpool_start_thread (ThreadPool *tp);
 static void threadpool_kill_thread (ThreadPool *tp);
 static void monitor_thread (gpointer data);
-static void socket_io_cleanup (SocketIOData *data);
-static MonoObject *get_io_event (MonoMList **list, gint event);
-static int get_events_from_list (MonoMList *list);
 static int get_event_from_state (MonoSocketAsyncResult *state);
-static void check_for_interruption_critical (void);
 
 static MonoClass *async_call_klass;
 static MonoClass *socket_async_call_klass;
 static MonoClass *process_async_call_klass;
 
+static GPtrArray *threads;
+mono_mutex_t threads_lock;
 static GPtrArray *wsqs;
 mono_mutex_t wsqs_lock;
 static gboolean suspended;
 
+static volatile gint32 monitor_njobs = 0;
+static volatile gint32 monitor_state;
+static MonoSemType monitor_sem;
+static MonoInternalThread *monitor_internal_thread;
+
 /* Hooks */
 static MonoThreadPoolFunc tp_start_func;
 static MonoThreadPoolFunc tp_finish_func;
@@ -183,7 +185,9 @@ enum {
        AIO_OP_LAST
 };
 
-#include <mono/metadata/tpool-poll.c>
+// #include <mono/metadata/tpool-poll.c>
+gpointer tp_poll_init (SocketIOData *data);
+
 #ifdef HAVE_EPOLL
 #include <mono/metadata/tpool-epoll.c>
 #elif defined(USE_KQUEUE_FOR_THREADPOOL)
@@ -209,16 +213,6 @@ is_corlib_type (MonoDomain *domain, MonoClass *klass)
        return klass->image == mono_defaults.corlib;
 }
 
-/*
- * Note that we call it is_socket_type() where 'socket' refers to the image
- * that contains the System.Net.Sockets.Socket type.
-*/
-static gboolean
-is_socket_type (MonoDomain *domain, MonoClass *klass)
-{
-       return is_system_type (domain, klass);
-}
-
 #define check_type_cached(domain, ASSEMBLY, _class, _namespace, _name, loc) do { \
        if (*loc) \
                return *loc == _class; \
@@ -231,8 +225,6 @@ is_socket_type (MonoDomain *domain, MonoClass *klass)
 
 #define check_corlib_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, corlib, _class, _namespace, _name, loc)
 
-#define check_socket_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, socket, _class, _namespace, _name, loc)
-
 #define check_system_type_cached(domain, _class, _namespace, _name, loc) check_type_cached (domain, system, _class, _namespace, _name, loc)
 
 static gboolean
@@ -241,26 +233,18 @@ is_corlib_asyncresult (MonoDomain *domain, MonoClass *klass)
        check_corlib_type_cached (domain, klass, "System.Runtime.Remoting.Messaging", "AsyncResult", &domain->corlib_asyncresult_class);
 }
 
-static gboolean
-is_socket (MonoDomain *domain, MonoClass *klass)
-{
-       check_socket_type_cached (domain, klass, "System.Net.Sockets", "Socket", &domain->socket_class);
-}
-
 static gboolean
 is_socketasyncresult (MonoDomain *domain, MonoClass *klass)
 {
-       return (klass->nested_in &&
-                       is_socket (domain, klass->nested_in) &&
-                       !strcmp (klass->name, "SocketAsyncResult"));
+       static MonoClass *socket_async_result_klass = NULL;
+       check_system_type_cached (domain, klass, "System.Net.Sockets", "SocketAsyncResult", &socket_async_result_klass);
 }
 
 static gboolean
 is_socketasynccall (MonoDomain *domain, MonoClass *klass)
 {
-       return (klass->nested_in &&
-                       is_socket (domain, klass->nested_in) &&
-                       !strcmp (klass->name, "SocketAsyncCall"));
+       static MonoClass *socket_async_callback_klass = NULL;
+       check_system_type_cached (domain, klass, "System.Net.Sockets", "SocketAsyncCallback", &socket_async_callback_klass);
 }
 
 static gboolean
@@ -287,7 +271,10 @@ is_sdp_asyncreadhandler (MonoDomain *domain, MonoClass *klass)
 
 #ifdef DISABLE_SOCKETS
 
-#define socket_io_cleanup(x)
+void
+socket_io_cleanup (SocketIOData *data)
+{
+}
 
 static int
 get_event_from_state (MonoSocketAsyncResult *state)
@@ -296,7 +283,7 @@ get_event_from_state (MonoSocketAsyncResult *state)
        return -1;
 }
 
-static int
+int
 get_events_from_list (MonoMList *list)
 {
        return 0;
@@ -304,7 +291,7 @@ get_events_from_list (MonoMList *list)
 
 #else
 
-static void
+void
 socket_io_cleanup (SocketIOData *data)
 {
        mono_mutex_lock (&data->io_lock);
@@ -342,7 +329,7 @@ get_event_from_state (MonoSocketAsyncResult *state)
        }
 }
 
-static int
+int
 get_events_from_list (MonoMList *list)
 {
        MonoSocketAsyncResult *state;
@@ -356,14 +343,6 @@ get_events_from_list (MonoMList *list)
        return events;
 }
 
-#define ICALL_RECV(x)  ves_icall_System_Net_Sockets_Socket_Receive_internal (\
-                               (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
-                                x->socket_flags, &x->error);
-
-#define ICALL_SEND(x)  ves_icall_System_Net_Sockets_Socket_Send_internal (\
-                               (SOCKET)(gssize)x->handle, x->buffer, x->offset, x->size,\
-                                x->socket_flags, &x->error);
-
 #endif /* !DISABLE_SOCKETS */
 
 static void
@@ -391,7 +370,7 @@ threadpool_jobs_dec (MonoObject *obj)
        return FALSE;
 }
 
-static MonoObject *
+MonoObject *
 get_io_event (MonoMList **list, gint event)
 {
        MonoObject *state;
@@ -433,6 +412,13 @@ mono_thread_pool_remove_socket (int sock)
        MonoSocketAsyncResult *state;
        MonoObject *ares;
 
+       if (use_ms_threadpool ()) {
+#ifndef DISABLE_SOCKETS
+               mono_threadpool_ms_io_remove_socket (sock);
+#endif
+               return;
+       }
+
        if (socket_io_data.inited == 0)
                return;
 
@@ -592,63 +578,9 @@ socket_io_filter (MonoObject *target, MonoObject *state)
 static MonoObject *
 mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
 {
-       ASyncCall *ac = (ASyncCall *)ares->object_data;
-       MonoObject *res, *exc = NULL;
-       MonoArray *out_args = NULL;
-       HANDLE wait_event = NULL;
-       MonoInternalThread *thread = mono_thread_internal_current ();
-
-       if (ares->execution_context) {
-               /* use captured ExecutionContext (if available) */
-               MONO_OBJECT_SETREF (ares, original_context, mono_thread_get_execution_context ());
-               mono_thread_set_execution_context (ares->execution_context);
-       } else {
-               ares->original_context = NULL;
-       }
+       MonoObject *exc = NULL;
 
-       if (ac == NULL) {
-               /* Fast path from ThreadPool.*QueueUserWorkItem */
-               void *pa = ares->async_state;
-               /* The debugger needs this */
-               thread->async_invoke_method = ((MonoDelegate*)ares->async_delegate)->method;
-               res = mono_runtime_delegate_invoke (ares->async_delegate, &pa, &exc);
-               thread->async_invoke_method = NULL;
-       } else {
-               MonoObject *cb_exc = NULL;
-
-               ac->msg->exc = NULL;
-               res = mono_message_invoke (ares->async_delegate, ac->msg, &exc, &out_args);
-               MONO_OBJECT_SETREF (ac, res, res);
-               MONO_OBJECT_SETREF (ac, msg->exc, exc);
-               MONO_OBJECT_SETREF (ac, out_args, out_args);
-
-               mono_monitor_enter ((MonoObject *) ares);
-               ares->completed = 1;
-               if (ares->handle != NULL)
-                       wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
-               mono_monitor_exit ((MonoObject *) ares);
-               /* notify listeners */
-               if (wait_event != NULL)
-                       SetEvent (wait_event);
-
-               /* call async callback if cb_method != null*/
-               if (ac != NULL && ac->cb_method) {
-                       void *pa = &ares;
-                       cb_exc = NULL;
-                       thread->async_invoke_method = ac->cb_method;
-                       mono_runtime_invoke (ac->cb_method, ac->cb_target, pa, &cb_exc);
-                       thread->async_invoke_method = NULL;
-                       exc = cb_exc;
-               } else {
-                       exc = NULL;
-               }
-       }
-
-       /* restore original thread execution context if flow isn't suppressed, i.e. non null */
-       if (ares->original_context) {
-               mono_thread_set_execution_context (ares->original_context);
-               ares->original_context = NULL;
-       }
+       mono_async_result_invoke (ares, &exc);
 
 #if DEBUG
        InterlockedDecrement (&tp->njobs);
@@ -656,6 +588,9 @@ mono_async_invoke (ThreadPool *tp, MonoAsyncResult *ares)
        if (!tp->is_io)
                InterlockedIncrement (&tp->nexecuted);
 
+       if (InterlockedDecrement (&monitor_njobs) == 0)
+               monitor_state = MONITOR_STATE_FALLING_ASLEEP;
+
        return exc;
 }
 
@@ -759,6 +694,9 @@ signal_handler (int signo)
 
 #define SAMPLES_PERIOD 500
 #define HISTORY_SIZE 10
+/* number of iteration without any jobs
+   in the queue before going to sleep */
+#define NUM_WAITING_ITERATIONS 10
 
 typedef struct {
        gint32 nexecuted;
@@ -766,12 +704,21 @@ typedef struct {
        gint8 nthreads_diff;
 } SamplesHistory;
 
+/*
+ * returns :
+ *  -  1 if the number of threads should increase
+ *  -  0 if it should not change
+ *  - -1 if it should decrease
+ *  - -2 in case of error
+ */
 static gint8
 monitor_heuristic (gint16 *current, gint16 *history_size, SamplesHistory *history, ThreadPool *tp)
 {
        int i;
-       gint8 decision;
+       gint8 decision G_GNUC_UNUSED;
        gint16 cur, max = 0;
+       gboolean all_waitsleepjoin;
+       MonoInternalThread *thread;
 
        /*
         * The following heuristic tries to approach the optimal number of threads to maximize jobs throughput. To
@@ -807,22 +754,43 @@ monitor_heuristic (gint16 *current, gint16 *history_size, SamplesHistory *histor
                history [cur].nthreads_diff = 1;
                decision = 2;
        } else {
-               max = cur == 0 ? 1 : 0;
-               for (i = 0; i < *history_size; i++) {
-                       if (i == cur)
-                               continue;
-                       if (history [i].nexecuted > history [max].nexecuted)
-                               max = i;
+               mono_mutex_lock (&threads_lock);
+               if (threads == NULL) {
+                       mono_mutex_unlock (&threads_lock);
+                       return -2;
                }
+               all_waitsleepjoin = TRUE;
+               for (i = 0; i < threads->len; ++i) {
+                       thread = g_ptr_array_index (threads, i);
+                       if (!(thread->state & ThreadState_WaitSleepJoin)) {
+                               all_waitsleepjoin = FALSE;
+                               break;
+                       }
+               }
+               mono_mutex_unlock (&threads_lock);
 
-               if (history [cur].nexecuted >= history [max].nexecuted) {
-                       /* we improved the situation, let's continue ! */
-                       history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? 1 : -1;
-                       decision = 3;
+               if (all_waitsleepjoin) {
+                       /* we might be in a condition of starvation/deadlock with tasks waiting for each others */
+                       history [cur].nthreads_diff = 1;
+                       decision = 5;
                } else {
-                       /* we made it worse, let's return to previous situation */
-                       history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? -1 : 1;
-                       decision = 4;
+                       max = cur == 0 ? 1 : 0;
+                       for (i = 0; i < *history_size; i++) {
+                               if (i == cur)
+                                       continue;
+                               if (history [i].nexecuted > history [max].nexecuted)
+                                       max = i;
+                       }
+
+                       if (history [cur].nexecuted >= history [max].nexecuted) {
+                               /* we improved the situation, let's continue ! */
+                               history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? 1 : -1;
+                               decision = 3;
+                       } else {
+                               /* we made it worse, let's return to previous situation */
+                               history [cur].nthreads_diff = history [cur].nthreads >= history [max].nthreads ? -1 : 1;
+                               decision = 4;
+                       }
                }
        }
 
@@ -842,6 +810,7 @@ monitor_thread (gpointer unused)
        int i;
 
        guint32 ms;
+       gint8 num_waiting_iterations = 0;
 
        gint16 history_size = 0, current = -1;
        SamplesHistory *history = malloc (sizeof (SamplesHistory) * HISTORY_SIZE);
@@ -853,6 +822,8 @@ monitor_thread (gpointer unused)
        while (1) {
                ms = SAMPLES_PERIOD;
                i = 10; //number of spurious awakes we tolerate before doing a round of rebalancing.
+               mono_gc_set_skip_thread (TRUE);
+               MONO_PREPARE_BLOCKING
                do {
                        guint32 ts;
                        ts = mono_msec_ticks ();
@@ -861,9 +832,10 @@ monitor_thread (gpointer unused)
                        ms -= (mono_msec_ticks () - ts);
                        if (mono_runtime_is_shutting_down ())
                                break;
-                       if (THREAD_WANTS_A_BREAK (thread))
-                               mono_thread_interruption_checkpoint ();
+                       check_for_interruption_critical ();
                } while (ms > 0 && i--);
+               MONO_FINISH_BLOCKING
+               mono_gc_set_skip_thread (FALSE);
 
                if (mono_runtime_is_shutting_down ())
                        break;
@@ -871,6 +843,31 @@ monitor_thread (gpointer unused)
                if (suspended)
                        continue;
 
+               /* threadpool is cleaning up */
+               if (async_tp.pool_status == 2 || async_io_tp.pool_status == 2)
+                       break;
+
+               MONO_PREPARE_BLOCKING
+               switch (monitor_state) {
+               case MONITOR_STATE_AWAKE:
+                       num_waiting_iterations = 0;
+                       break;
+               case MONITOR_STATE_FALLING_ASLEEP:
+                       if (++num_waiting_iterations == NUM_WAITING_ITERATIONS) {
+                               if (monitor_state == MONITOR_STATE_FALLING_ASLEEP && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_SLEEPING, MONITOR_STATE_FALLING_ASLEEP) == MONITOR_STATE_FALLING_ASLEEP) {
+                                       MONO_SEM_WAIT (&monitor_sem);
+
+                                       num_waiting_iterations = 0;
+                                       current = -1;
+                                       history_size = 0;
+                               }
+                       }
+                       break;
+               case MONITOR_STATE_SLEEPING:
+                       g_assert_not_reached ();
+               }
+               MONO_FINISH_BLOCKING
+
                for (i = 0; i < 2; i++) {
                        ThreadPool *tp;
                        tp = pools [i];
@@ -881,9 +878,9 @@ monitor_thread (gpointer unused)
                        } else {
                                gint8 nthreads_diff = monitor_heuristic (&current, &history_size, history, tp);
 
-                               if (nthreads_diff > 0)
+                               if (nthreads_diff == 1)
                                        threadpool_start_thread (tp);
-                               else if (nthreads_diff < 0)
+                               else if (nthreads_diff == -1)
                                        threadpool_kill_thread (tp);
                        }
                }
@@ -893,6 +890,11 @@ monitor_thread (gpointer unused)
 void
 mono_thread_pool_init_tls (void)
 {
+       if (use_ms_threadpool ()) {
+               mono_threadpool_ms_init_tls ();
+               return;
+       }
+
        mono_wsq_init ();
 }
 
@@ -901,8 +903,15 @@ mono_thread_pool_init (void)
 {
        gint threads_per_cpu = 1;
        gint thread_count;
-       gint cpu_count = mono_cpu_count ();
+       gint cpu_count;
        int result;
+       
+       if (use_ms_threadpool ()) {
+               mono_threadpool_ms_init ();
+               return;
+       }
+
+       cpu_count = mono_cpu_count ();
 
        if (tp_inited == 2)
                return;
@@ -932,6 +941,10 @@ mono_thread_pool_init (void)
        async_call_klass = mono_class_from_name (mono_defaults.corlib, "System", "MonoAsyncCall");
        g_assert (async_call_klass);
 
+       mono_mutex_init (&threads_lock);
+       threads = g_ptr_array_sized_new (thread_count);
+       g_assert (threads);
+
        mono_mutex_init_recursive (&wsqs_lock);
        wsqs = g_ptr_array_sized_new (MAX (100 * cpu_count, thread_count));
 
@@ -953,6 +966,10 @@ mono_thread_pool_init (void)
        signal (SIGALRM, signal_handler);
        alarm (2);
 #endif
+
+       MONO_SEM_INIT (&monitor_sem, 0);
+       monitor_state = MONITOR_STATE_AWAKE;
+       monitor_njobs = 0;
 }
 
 static MonoAsyncResult *
@@ -974,45 +991,63 @@ icall_append_io_job (MonoObject *target, MonoSocketAsyncResult *state)
        MonoAsyncResult *ares;
 
        ares = create_simple_asyncresult (target, (MonoObject *) state);
+
+       if (use_ms_threadpool ()) {
+#ifndef DISABLE_SOCKETS
+               mono_threadpool_ms_io_add (ares, state);
+#endif
+               return;
+       }
+
        socket_io_add (ares, state);
 }
 
 MonoAsyncResult *
-mono_thread_pool_add (MonoObject *target, MonoMethodMessage *msg, MonoDelegate *async_callback,
-                     MonoObject *state)
+mono_thread_pool_begin_invoke (MonoDomain *domain, MonoObject *target, MonoMethod *method, gpointer *params)
 {
-       MonoDomain *domain = mono_domain_get ();
-       MonoAsyncResult *ares;
-       ASyncCall *ac;
+       MonoMethodMessage *message;
+       MonoAsyncResult *async_result;
+       MonoAsyncCall *async_call;
+       MonoDelegate *async_callback = NULL;
+       MonoObject *state = NULL;
+
+       if (use_ms_threadpool ())
+               return mono_threadpool_ms_begin_invoke (domain, target, method, params);
 
-       ac = (ASyncCall*)mono_object_new (domain, async_call_klass);
-       MONO_OBJECT_SETREF (ac, msg, msg);
-       MONO_OBJECT_SETREF (ac, state, state);
+       message = mono_method_call_message_new (method, params, mono_get_delegate_invoke (method->klass), (params != NULL) ? (&async_callback) : NULL, (params != NULL) ? (&state) : NULL);
+
+       async_call = (MonoAsyncCall*)mono_object_new (domain, async_call_klass);
+       MONO_OBJECT_SETREF (async_call, msg, message);
+       MONO_OBJECT_SETREF (async_call, state, state);
 
        if (async_callback) {
-               ac->cb_method = mono_get_delegate_invoke (((MonoObject *)async_callback)->vtable->klass);
-               MONO_OBJECT_SETREF (ac, cb_target, async_callback);
+               async_call->cb_method = mono_get_delegate_invoke (((MonoObject*) async_callback)->vtable->klass);
+               MONO_OBJECT_SETREF (async_call, cb_target, async_callback);
        }
 
-       ares = mono_async_result_new (domain, NULL, ac->state, NULL, (MonoObject*)ac);
-       MONO_OBJECT_SETREF (ares, async_delegate, target);
+       async_result = mono_async_result_new (domain, NULL, async_call->state, NULL, (MonoObject*) async_call);
+       MONO_OBJECT_SETREF (async_result, async_delegate, target);
 
 #ifndef DISABLE_SOCKETS
        if (socket_io_filter (target, state)) {
-               socket_io_add (ares, (MonoSocketAsyncResult *) state);
-               return ares;
+               socket_io_add (async_result, (MonoSocketAsyncResult *) state);
+               return async_result;
        }
 #endif
-       threadpool_append_job (&async_tp, (MonoObject *) ares);
-       return ares;
+       threadpool_append_job (&async_tp, (MonoObject *) async_result);
+       return async_result;
 }
 
 MonoObject *
-mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
+mono_thread_pool_end_invoke (MonoAsyncResult *ares, MonoArray **out_args, MonoObject **exc)
 {
-       ASyncCall *ac;
+       MonoAsyncCall *ac;
        HANDLE wait_event;
 
+       if (use_ms_threadpool ()) {
+               return mono_threadpool_ms_end_invoke (ares, out_args, exc);
+       }
+
        *exc = NULL;
        *out_args = NULL;
 
@@ -1036,12 +1071,14 @@ mono_thread_pool_finish (MonoAsyncResult *ares, MonoArray **out_args, MonoObject
                        wait_event = mono_wait_handle_get_handle ((MonoWaitHandle *) ares->handle);
                }
                mono_monitor_exit ((MonoObject *) ares);
+               MONO_PREPARE_BLOCKING
                WaitForSingleObjectEx (wait_event, INFINITE, TRUE);
+               MONO_FINISH_BLOCKING
        } else {
                mono_monitor_exit ((MonoObject *) ares);
        }
 
-       ac = (ASyncCall *) ares->object_data;
+       ac = (MonoAsyncCall *) ares->object_data;
        g_assert (ac != NULL);
        *exc = ac->msg->exc; /* FIXME: GC add write barrier */
        *out_args = ac->out_args;
@@ -1064,6 +1101,11 @@ threadpool_kill_idle_threads (ThreadPool *tp)
 void
 mono_thread_pool_cleanup (void)
 {
+       if (use_ms_threadpool ()) {
+               mono_threadpool_ms_cleanup ();
+               return;
+       }
+
        if (InterlockedExchange (&async_io_tp.pool_status, 2) == 1) {
                socket_io_cleanup (&socket_io_data); /* Empty when DISABLE_SOCKETS is defined */
                threadpool_kill_idle_threads (&async_io_tp);
@@ -1079,6 +1121,14 @@ mono_thread_pool_cleanup (void)
                threadpool_kill_idle_threads (&async_tp);
                threadpool_free_queue (&async_tp);
        }
+       
+       if (threads) {
+               mono_mutex_lock (&threads_lock);
+               if (threads)
+                       g_ptr_array_free (threads, FALSE);
+               threads = NULL;
+               mono_mutex_unlock (&threads_lock);
+       }
 
        if (wsqs) {
                mono_mutex_lock (&wsqs_lock);
@@ -1089,6 +1139,8 @@ mono_thread_pool_cleanup (void)
                mono_mutex_unlock (&wsqs_lock);
                MONO_SEM_DESTROY (&async_tp.new_job);
        }
+
+       MONO_SEM_DESTROY (&monitor_sem);
 }
 
 static gboolean
@@ -1096,6 +1148,7 @@ threadpool_start_thread (ThreadPool *tp)
 {
        gint n;
        guint32 stack_size;
+       MonoInternalThread *thread;
 
        stack_size = (!tp->is_io) ? 0 : SMALL_STACK;
        while (!mono_runtime_is_shutting_down () && (n = tp->nthreads) < tp->max_threads) {
@@ -1103,7 +1156,15 @@ threadpool_start_thread (ThreadPool *tp)
 #ifndef DISABLE_PERFCOUNTERS
                        mono_perfcounter_update_value (tp->pc_nthreads, TRUE, 1);
 #endif
-                       mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
+                       if (tp->is_io) {
+                               thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
+                       } else {
+                               mono_mutex_lock (&threads_lock);
+                               thread = mono_thread_create_internal (mono_get_root_domain (), tp->async_invoke, tp, TRUE, stack_size);
+                               g_assert (threads != NULL);
+                               g_ptr_array_add (threads, thread);
+                               mono_mutex_unlock (&threads_lock);
+                       }
                        return TRUE;
                }
        }
@@ -1137,6 +1198,12 @@ threadpool_append_job (ThreadPool *tp, MonoObject *ar)
        threadpool_append_jobs (tp, &ar, 1);
 }
 
+void
+threadpool_append_async_io_jobs (MonoObject **jobs, gint njobs)
+{
+       threadpool_append_jobs (&async_io_tp, jobs, njobs);
+}
+
 static void
 threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
 {
@@ -1148,7 +1215,8 @@ threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
 
        if (tp->pool_status == 0 && InterlockedCompareExchange (&tp->pool_status, 1, 0) == 0) {
                if (!tp->is_io) {
-                       mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK);
+                       monitor_internal_thread = mono_thread_create_internal (mono_get_root_domain (), monitor_thread, NULL, TRUE, SMALL_STACK);
+                       monitor_internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
                        threadpool_start_thread (tp);
                }
                /* Create on demand up to min_threads to avoid startup penalty for apps that don't use
@@ -1159,6 +1227,14 @@ threadpool_append_jobs (ThreadPool *tp, MonoObject **jobs, gint njobs)
                }
        }
 
+       InterlockedAdd (&monitor_njobs, njobs);
+
+       if (monitor_state == MONITOR_STATE_SLEEPING && InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_SLEEPING) == MONITOR_STATE_SLEEPING)
+               MONO_SEM_POST (&monitor_sem);
+
+       if (monitor_state == MONITOR_STATE_FALLING_ASLEEP)
+               InterlockedCompareExchange (&monitor_state, MONITOR_STATE_AWAKE, MONITOR_STATE_FALLING_ASLEEP);
+
        for (i = 0; i < njobs; i++) {
                ar = jobs [i];
                if (ar == NULL || mono_domain_is_unloading (ar->vtable->domain))
@@ -1234,8 +1310,15 @@ gboolean
 mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
 {
        HANDLE sem_handle;
-       int result = TRUE;
-       guint32 start_time = 0;
+       int result;
+       guint32 start_time;
+
+       if (use_ms_threadpool ()) {
+               return mono_threadpool_ms_remove_domain_jobs (domain, timeout);
+       }
+
+       result = TRUE;
+       start_time = 0;
 
        g_assert (domain->state == MONO_APPDOMAIN_UNLOADING);
 
@@ -1265,7 +1348,9 @@ mono_thread_pool_remove_domain_jobs (MonoDomain *domain, int timeout)
        if (domain->threadpool_jobs && timeout != -1)
                start_time = mono_msec_ticks ();
        while (domain->threadpool_jobs) {
+               MONO_PREPARE_BLOCKING
                WaitForSingleObject (sem_handle, timeout);
+               MONO_FINISH_BLOCKING
                if (timeout != -1 && (mono_msec_ticks () - start_time) > timeout) {
                        result = FALSE;
                        break;
@@ -1287,6 +1372,10 @@ threadpool_free_queue (ThreadPool *tp)
 gboolean
 mono_thread_pool_is_queue_array (MonoArray *o)
 {
+       if (use_ms_threadpool ()) {
+               return mono_threadpool_ms_is_queue_array (o);
+       }
+
        // gpointer obj = o;
 
        // FIXME: need some fix in sgen code.
@@ -1360,7 +1449,9 @@ try_steal (MonoWSQ *local_wsq, gpointer *data, gboolean retry)
                if (mono_runtime_is_shutting_down ())
                        return;
 
+               MONO_PREPARE_BLOCKING
                mono_mutex_lock (&wsqs_lock);
+               MONO_FINISH_BLOCKING
                for (i = 0; wsqs != NULL && i < wsqs->len; i++) {
                        MonoWSQ *wsq;
 
@@ -1420,7 +1511,7 @@ clear_thread_state (void)
                ves_icall_System_Threading_Thread_SetState (thread, ThreadState_Background);
 }
 
-static void
+void
 check_for_interruption_critical (void)
 {
        MonoInternalThread *thread;
@@ -1481,14 +1572,6 @@ async_invoke_thread (gpointer data)
                                MonoSocketAsyncResult *state = (MonoSocketAsyncResult *) data;
                                is_socket = is_socketasyncresult (domain, klass);
                                ar = state->ares;
-                               switch (state->operation) {
-                               case AIO_OP_RECEIVE:
-                                       state->total = ICALL_RECV (state);
-                                       break;
-                               case AIO_OP_SEND:
-                                       state->total = ICALL_SEND (state);
-                                       break;
-                               }
                        }
 #endif
                        /* worker threads invokes methods in different domains,
@@ -1564,6 +1647,7 @@ async_invoke_thread (gpointer data)
                        }
 
                        mono_gc_set_skip_thread (TRUE);
+                       MONO_PREPARE_BLOCKING
 
 #if defined(__OpenBSD__)
                        while (mono_cq_count (tp->queue) == 0 && (res = mono_sem_wait (&tp->new_job, TRUE)) == -1) {// && errno == EINTR) {
@@ -1576,6 +1660,7 @@ async_invoke_thread (gpointer data)
                        }
                        InterlockedDecrement (&tp->waiting);
 
+                       MONO_FINISH_BLOCKING
                        mono_gc_set_skip_thread (FALSE);
 
                        if (mono_runtime_is_shutting_down ())
@@ -1613,6 +1698,16 @@ async_invoke_thread (gpointer data)
 
                                        if (tp_finish_func)
                                                tp_finish_func (tp_hooks_user_data);
+
+                                       if (!tp->is_io) {
+                                               if (threads) {
+                                                       mono_mutex_lock (&threads_lock);
+                                                       if (threads)
+                                                               g_ptr_array_remove_fast (threads, mono_thread_current ()->internal_thread);
+                                                       mono_mutex_unlock (&threads_lock);
+                                               }
+                                       }
+
                                        return;
                                }
                        }
@@ -1748,6 +1843,10 @@ mono_internal_thread_unhandled_exception (MonoObject* exc)
 void
 mono_thread_pool_suspend (void)
 {
+       if (use_ms_threadpool ()) {
+               mono_threadpool_ms_suspend ();
+               return;
+       }
        suspended = TRUE;
 }
 
@@ -1757,5 +1856,9 @@ mono_thread_pool_suspend (void)
 void
 mono_thread_pool_resume (void)
 {
+       if (use_ms_threadpool ()) {
+               mono_threadpool_ms_resume ();
+               return;
+       }
        suspended = FALSE;
 }