Rework ReaderWriterLockSlim to use simpler Interlocked arithmetic.
[mono.git] / mcs / class / corlib / System.Threading / Thread.cs
index fc5352f57ba44f0ccc4deb4211047bba2e015c69..355fb0eb5d7b5497366486c8eddddcd62a14e57e 100644 (file)
@@ -39,19 +39,11 @@ using System.IO;
 using System.Collections;
 using System.Reflection;
 using System.Security;
-
-#if NET_2_0
 using System.Runtime.ConstrainedExecution;
-#endif
 
 namespace System.Threading {
 
-#if NET_2_0
        internal class InternalThread : CriticalFinalizerObject {
-#else
-       internal class InternalThread {
-#endif
-
 #pragma warning disable 169, 414, 649
                #region Sync with metadata/object-internals.h
                int lock_thread_id;
@@ -79,7 +71,9 @@ namespace System.Threading {
                private UIntPtr static_data; /* GC-tracked */
                private IntPtr jit_data;
                private IntPtr lock_data;
-               Context current_appcontext;
+               /* current System.Runtime.Remoting.Contexts.Context instance
+                  keep as an object to avoid triggering its class constructor when not needed */
+               private object current_appcontext;
                internal int stack_size;
                private IntPtr appdomain_refs;
                private int interruption_requested;
@@ -112,9 +106,7 @@ namespace System.Threading {
                #endregion
 #pragma warning restore 169, 414, 649
 
-#if NET_2_0
                internal int managed_id;
-#endif
 
                internal byte[] _serialized_principal;
                internal int _serialized_principal_version;
@@ -134,28 +126,23 @@ namespace System.Threading {
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern void Thread_free_internal(IntPtr handle);
 
-#if NET_2_0
                [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
-#endif
                ~InternalThread() {
-                               Thread_free_internal(system_thread_handle);
+                       Thread_free_internal(system_thread_handle);
                }
        }
 
        [ClassInterface (ClassInterfaceType.None)]
-#if NET_2_0
        [ComVisible (true)]
        [ComDefaultInterface (typeof (_Thread))]
        public sealed class Thread : CriticalFinalizerObject, _Thread {
-#else
-       public sealed class Thread : _Thread {
-#endif
-
+#pragma warning disable 414            
                #region Sync with metadata/object-internals.h
                private InternalThread internal_thread;
                object start_obj;
                private ExecutionContext ec_to_set;
                #endregion
+#pragma warning restore 414
 
                IPrincipal principal;
                int principal_version;
@@ -178,9 +165,7 @@ namespace System.Threading {
                private MulticastDelegate threadstart;
                //private string thread_name=null;
 
-#if NET_2_0
                private static int _managed_id_counter;
-#endif
 
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern void ConstructInternalThread ();
@@ -212,7 +197,7 @@ namespace System.Threading {
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
 
-#if !NET_2_1
+#if !MOONLIGHT
                public static IPrincipal CurrentPrincipal {
                        get {
                                Thread th = CurrentThread;
@@ -263,9 +248,7 @@ namespace System.Threading {
                private extern static InternalThread CurrentInternalThread_internal();
 
                public static Thread CurrentThread {
-#if NET_2_0
                        [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
-#endif
                        get {
                                if (current_thread == null)
                                        current_thread = new Thread (CurrentInternalThread_internal ());
@@ -279,7 +262,7 @@ namespace System.Threading {
                        }
                }
 
-#if !NET_2_1 || MONOTOUCH
+#if !MOONLIGHT
                // Stores a hash keyed by strings of LocalDataStoreSlot objects
                static Hashtable datastorehash;
                private static object datastore_lock = new object ();
@@ -386,25 +369,31 @@ namespace System.Threading {
                        ResetAbort_internal ();
                }
 
+#if NET_4_0 || BOOTSTRAP_NET_4_0
+               [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
+               [MethodImplAttribute(MethodImplOptions.InternalCall)]
+               public extern static bool Yield ();
+#endif
+
+
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern static void Sleep_internal(int ms);
 
-               public static void Sleep(int millisecondsTimeout) {
-                       if((millisecondsTimeout<0) && (millisecondsTimeout != Timeout.Infinite)) {
-                               throw new ArgumentException("Negative timeout");
-                       }
-                       Sleep_internal(millisecondsTimeout);
+               public static void Sleep (int millisecondsTimeout)
+               {
+                       if (millisecondsTimeout < Timeout.Infinite)
+                               throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
+
+                       Sleep_internal (millisecondsTimeout);
                }
 
-               public static void Sleep(TimeSpan timeout) {
-                       // LAMESPEC: says to throw ArgumentException too
-                       int ms=Convert.ToInt32(timeout.TotalMilliseconds);
-                       
-                       if(ms < 0 || ms > Int32.MaxValue) {
-                               throw new ArgumentOutOfRangeException("Timeout out of range");
-                       }
+               public static void Sleep (TimeSpan timeout)
+               {
+                       long ms = (long) timeout.TotalMilliseconds;
+                       if (ms < Timeout.Infinite || ms > Int32.MaxValue)
+                               throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
 
-                       Sleep_internal(ms);
+                       Sleep_internal ((int) ms);
                }
 
                // Returns the system thread handle
@@ -422,10 +411,8 @@ namespace System.Threading {
                        internal_thread = it;
                }
 
-#if !NET_2_1
-#if NET_2_0
+#if !MOONLIGHT
                [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
-#endif
                public ApartmentState ApartmentState {
                        get {
                                if ((ThreadState & ThreadState.Stopped) != 0)
@@ -434,24 +421,8 @@ namespace System.Threading {
                                return (ApartmentState)Internal.apartment_state;
                        }
 
-                       set     {
-#if NET_2_0
+                       set {
                                TrySetApartmentState (value);
-#else
-                               /* Only throw this exception when
-                                * changing the state of another
-                                * thread.  See bug 324338
-                                */
-                               if ((this != CurrentThread) &&
-                                   (ThreadState & ThreadState.Unstarted) == 0)
-                                       throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
-
-                               if (value != ApartmentState.STA && value != ApartmentState.MTA)
-                                       throw new ArgumentOutOfRangeException ("value is not a valid apartment state.");
-
-                               if ((ApartmentState)Internal.apartment_state == ApartmentState.Unknown)
-                                       Internal.apartment_state = (byte)value;
-#endif
                        }
                }
 #endif // !NET_2_1
@@ -617,8 +588,6 @@ namespace System.Threading {
                        }
                        
                        set {
-                               Internal.in_currentculture = true;
-
                                if (value == null)
                                        throw new ArgumentNullException ("value");
 
@@ -626,6 +595,7 @@ namespace System.Threading {
                                if (culture == value)
                                        return;
 
+                               Internal.in_currentculture = true;
                                try {
                                        SetCachedCurrentUICulture (value);
 
@@ -718,7 +688,7 @@ namespace System.Threading {
                        }
                }
 
-#if !NET_2_1
+#if !MOONLIGHT
                public ThreadPriority Priority {
                        get {
                                return(ThreadPriority.Lowest);
@@ -745,7 +715,7 @@ namespace System.Threading {
                        Abort_internal (Internal, null);
                }
 
-#if !NET_2_1
+#if !MOONLIGHT
                [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
                public void Abort (object stateInfo) 
                {
@@ -777,22 +747,20 @@ namespace System.Threading {
 
                public bool Join(int millisecondsTimeout)
                {
-                       if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout < 0)
-                               throw new ArgumentException ("Timeout less than zero", "millisecondsTimeout");
+                       if (millisecondsTimeout < Timeout.Infinite)
+                               throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
 
-                       return Join_internal(Internal, millisecondsTimeout, Internal.system_thread_handle);
+                       return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
                }
 
-#if !NET_2_1
+#if !MOONLIGHT
                public bool Join(TimeSpan timeout)
                {
-                       // LAMESPEC: says to throw ArgumentException too
-                       int ms=Convert.ToInt32(timeout.TotalMilliseconds);
-                       
-                       if(ms < 0 || ms > Int32.MaxValue) {
-                               throw new ArgumentOutOfRangeException("timeout out of range");
-                       }
-                       return Join_internal(Internal, ms, Internal.system_thread_handle);
+                       long ms = (long) timeout.TotalMilliseconds;
+                       if (ms < Timeout.Infinite || ms > Int32.MaxValue)
+                               throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
+
+                       return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
                }
 #endif
 
@@ -801,13 +769,11 @@ namespace System.Threading {
                public extern static void MemoryBarrier ();
 #endif
 
-#if !NET_2_1
+#if !MOONLIGHT
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern void Resume_internal();
 
-#if NET_2_0
                [Obsolete ("")]
-#endif
                [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
                public void Resume () 
                {
@@ -819,9 +785,7 @@ namespace System.Threading {
                private extern static void SpinWait_nop ();
 
 
-#if NET_2_0
                [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
-#endif
                public static void SpinWait (int iterations) 
                {
                        if (iterations < 0)
@@ -832,7 +796,7 @@ namespace System.Threading {
                        }
                }
 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                private void StartSafe ()
                {
                        current_thread = this;
@@ -876,32 +840,21 @@ namespace System.Threading {
                {
                        current_thread = this;
 
-#if NET_2_0
                        if (threadstart is ThreadStart) {
                                ((ThreadStart) threadstart) ();
                        } else {
                                ((ParameterizedThreadStart) threadstart) (start_obj);
                        }
-#else
-                       ((ThreadStart) threadstart) ();
-#endif
                }
 
                public void Start() {
                        // propagate informations from the original thread to the new thread
-#if NET_2_0
                        if (!ExecutionContext.IsFlowSuppressed ())
                                ec_to_set = ExecutionContext.Capture ();
-#else
-                       // before 2.0 this was only used for security (mostly CAS) so we
-                       // do this only if the security manager is active
-                       if (SecurityManager.SecurityEnabled)
-                               ec_to_set = ExecutionContext.Capture ();
-#endif
                        Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
 
                        // Thread_internal creates and starts the new thread, 
-#if NET_2_1 && !MONOTOUCH
+#if MOONLIGHT
                        if (Thread_internal((ThreadStart) StartSafe) == (IntPtr) 0)
 #else
                        if (Thread_internal((ThreadStart) StartUnsafe) == (IntPtr) 0)
@@ -909,13 +862,11 @@ namespace System.Threading {
                                throw new SystemException ("Thread creation failed.");
                }
 
-#if !NET_2_1
+#if !MOONLIGHT
                [MethodImplAttribute(MethodImplOptions.InternalCall)]
                private extern static void Suspend_internal(InternalThread thread);
 
-#if NET_2_0
                [Obsolete ("")]
-#endif
                [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
                public void Suspend ()
                {
@@ -1024,7 +975,6 @@ namespace System.Threading {
                
 #endif
 
-#if NET_2_0
                private static int GetNewManagedId() {
                        return Interlocked.Increment(ref _managed_id_counter);
                }
@@ -1106,7 +1056,7 @@ namespace System.Threading {
                        // Managed and native threads are currently bound together.
                }
 
-#if !NET_2_1
+#if !MOONLIGHT
                public ApartmentState GetApartmentState ()
                {
                        return (ApartmentState)Internal.apartment_state;
@@ -1147,25 +1097,14 @@ namespace System.Threading {
                        start_obj = parameter;
                        Start ();
                }
-#else
-               internal ExecutionContext ExecutionContext {
-                       get {
-                               if (_ec == null)
-                                       _ec = new ExecutionContext ();
-                               return _ec;
-                       }
-               }
-#endif
 
-#if !NET_2_1
+#if !MOONLIGHT
                // NOTE: This method doesn't show in the class library status page because
                // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
                // But it's there!
                [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
                [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
-#if NET_2_0
                [Obsolete ("see CompressedStack class")]
-#endif
 #if NET_1_1
                public
 #else
@@ -1185,9 +1124,7 @@ namespace System.Threading {
                // But it's there!
                [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
                [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
-#if NET_2_0
                [Obsolete ("see CompressedStack class")]
-#endif
 #if NET_1_1
                public
 #else