Example #1
0
        private static void StartThread(IntPtr parameter)
        {
            GCHandle threadHandle = (GCHandle)parameter;
            Thread   thread       = (Thread)threadHandle.Target;
            Delegate threadStart  = thread._threadStart;
            // Get the value before clearing the ThreadState.Unstarted bit
            object threadStartArg = thread._threadStartArg;

            try
            {
                t_currentThread = thread;
                System.Threading.ManagedThreadId.SetForCurrentThread(thread._managedThreadId);
                thread.InitializeComOnNewThread();
            }
            catch (OutOfMemoryException)
            {
#if TARGET_UNIX
                // This should go away once OnThreadExit stops using t_currentThread to signal
                // shutdown of the thread on Unix.
                thread._stopped.Set();
#endif
                // Terminate the current thread. The creator thread will throw a ThreadStartException.
                return;
            }

            // Report success to the creator thread, which will free threadHandle and _threadStartArg
            thread.ClearThreadStateBit(ThreadState.Unstarted);

            if (thread._startCulture != null)
            {
                CultureInfo.CurrentCulture = thread._startCulture;
                thread._startCulture       = null;
            }

            if (thread._startUICulture != null)
            {
                CultureInfo.CurrentUICulture = thread._startUICulture;
                thread._startUICulture       = null;
            }

            try
            {
                // The Thread cannot be started more than once, so we may clean up the delegate
                thread._threadStart = null;

                ParameterizedThreadStart paramThreadStart = threadStart as ParameterizedThreadStart;
                if (paramThreadStart != null)
                {
                    paramThreadStart(threadStartArg);
                }
                else
                {
                    ((ThreadStart)threadStart)();
                }
            }
            finally
            {
                thread.SetThreadStateBit(ThreadState.Stopped);
            }
        }