2 // System.Threading.Thread.cs
5 // Dick Porter (dick@ximian.com)
7 // (C) Ximian, Inc. http://www.ximian.com
8 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.Runtime.Remoting.Contexts;
31 using System.Runtime.Serialization;
32 using System.Runtime.Serialization.Formatters.Binary;
33 using System.Security.Permissions;
34 using System.Security.Principal;
35 using System.Globalization;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.InteropServices;
39 using System.Collections;
40 using System.Reflection;
41 using System.Security;
42 using System.Runtime.ConstrainedExecution;
44 namespace System.Threading {
46 internal class InternalThread : CriticalFinalizerObject {
47 #pragma warning disable 169, 414, 649
48 #region Sync with metadata/object-internals.h
50 // stores a thread handle
51 internal IntPtr system_thread_handle;
53 /* Note this is an opaque object (an array), not a CultureInfo */
54 private object cached_culture_info;
55 private IntPtr unused0;
56 internal bool threadpool_thread;
57 /* accessed only from unmanaged code */
60 private ThreadState state;
61 private object abort_exc;
62 private int abort_state_handle;
63 /* thread_id is only accessed from unmanaged code */
64 internal Int64 thread_id;
66 /* start_notify is used by the runtime to signal that Start()
69 private IntPtr start_notify;
70 private IntPtr stack_ptr;
71 private UIntPtr static_data; /* GC-tracked */
72 private IntPtr jit_data;
73 private IntPtr lock_data;
74 /* current System.Runtime.Remoting.Contexts.Context instance
75 keep as an object to avoid triggering its class constructor when not needed */
76 private object current_appcontext;
77 internal int stack_size;
78 private IntPtr appdomain_refs;
79 private int interruption_requested;
80 private IntPtr suspend_event;
81 private IntPtr suspended_event;
82 private IntPtr resume_event;
83 private IntPtr synch_cs;
84 private bool thread_dump_requested;
85 private IntPtr end_stack;
86 private bool thread_interrupt_requested;
87 internal byte apartment_state;
88 internal volatile int critical_region_level;
90 private IntPtr manage_callback;
91 private object pending_exception;
92 /* This is the ExecutionContext that will be set by
93 start_wrapper() in the runtime. */
94 private ExecutionContext ec_to_set;
96 private IntPtr interrupt_on_stop;
99 * These fields are used to avoid having to increment corlib versions
100 * when a new field is added to the unmanaged MonoThread structure.
102 private IntPtr unused3;
103 private IntPtr unused4;
104 private IntPtr unused5;
105 private IntPtr unused6;
107 #pragma warning restore 169, 414, 649
109 internal int managed_id;
111 internal byte[] _serialized_principal;
112 internal int _serialized_principal_version;
114 internal byte[] serialized_culture_info;
115 internal byte[] serialized_ui_culture_info;
117 /* If the current_lcid() isn't known by CultureInfo,
118 * it will throw an exception which may cause
119 * String.Concat to try and recursively look up the
120 * CurrentCulture, which will throw an exception, etc.
121 * Use a boolean to short-circuit this scenario.
123 internal bool in_currentculture=false;
125 // Closes the system thread handle
126 [MethodImplAttribute(MethodImplOptions.InternalCall)]
127 private extern void Thread_free_internal(IntPtr handle);
129 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
131 Thread_free_internal(system_thread_handle);
135 [ClassInterface (ClassInterfaceType.None)]
137 [ComDefaultInterface (typeof (_Thread))]
138 public sealed class Thread : CriticalFinalizerObject, _Thread {
139 #pragma warning disable 414
140 #region Sync with metadata/object-internals.h
141 private InternalThread internal_thread;
143 private ExecutionContext ec_to_set;
145 #pragma warning restore 414
147 IPrincipal principal;
148 int principal_version;
150 // the name of local_slots, current_thread and _ec is
151 // important because they are used by the runtime.
153 static object[] local_slots;
156 static Thread current_thread;
158 /* The actual ExecutionContext of the thread. It's
159 ThreadStatic so that it's not shared between
162 static ExecutionContext _ec;
164 // can be both a ThreadStart and a ParameterizedThreadStart
165 private MulticastDelegate threadstart;
166 //private string thread_name=null;
168 private static int _managed_id_counter;
170 [MethodImplAttribute(MethodImplOptions.InternalCall)]
171 private extern void ConstructInternalThread ();
173 private InternalThread Internal {
175 if (internal_thread == null)
176 ConstructInternalThread ();
177 return internal_thread;
181 public static Context CurrentContext {
182 [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
184 return(AppDomain.InternalGetContext ());
189 * These two methods return an array in the target
190 * domain with the same content as the argument. If
191 * the argument is already in the target domain, then
192 * the argument is returned, otherwise a copy.
194 [MethodImplAttribute(MethodImplOptions.InternalCall)]
195 private extern static byte[] ByteArrayToRootDomain (byte[] arr);
197 [MethodImplAttribute(MethodImplOptions.InternalCall)]
198 private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
201 public static IPrincipal CurrentPrincipal {
203 Thread th = CurrentThread;
205 if (th.principal_version != th.Internal._serialized_principal_version)
208 if (th.principal != null)
211 if (th.Internal._serialized_principal != null) {
213 BinaryFormatter bf = new BinaryFormatter ();
214 MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
215 th.principal = (IPrincipal) bf.Deserialize (ms);
216 th.principal_version = th.Internal._serialized_principal_version;
218 } catch (Exception) {
222 th.principal = GetDomain ().DefaultPrincipal;
223 th.principal_version = th.Internal._serialized_principal_version;
226 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
228 Thread th = CurrentThread;
230 ++th.Internal._serialized_principal_version;
232 BinaryFormatter bf = new BinaryFormatter ();
233 MemoryStream ms = new MemoryStream ();
234 bf.Serialize (ms, value);
235 th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
236 } catch (Exception) {
237 th.Internal._serialized_principal = null;
240 th.principal = value;
241 th.principal_version = th.Internal._serialized_principal_version;
246 // Looks up the object associated with the current thread
247 [MethodImplAttribute(MethodImplOptions.InternalCall)]
248 private extern static InternalThread CurrentInternalThread_internal();
250 public static Thread CurrentThread {
251 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
253 if (current_thread == null)
254 current_thread = new Thread (CurrentInternalThread_internal ());
255 return current_thread;
259 internal static int CurrentThreadId {
261 return (int)(CurrentThread.internal_thread.thread_id);
266 // Stores a hash keyed by strings of LocalDataStoreSlot objects
267 static Hashtable datastorehash;
268 private static object datastore_lock = new object ();
270 private static void InitDataStoreHash () {
271 lock (datastore_lock) {
272 if (datastorehash == null) {
273 datastorehash = Hashtable.Synchronized(new Hashtable());
278 public static LocalDataStoreSlot AllocateNamedDataSlot (string name) {
279 lock (datastore_lock) {
280 if (datastorehash == null)
281 InitDataStoreHash ();
282 LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
284 // This exception isnt documented (of
285 // course) but .net throws it
286 throw new ArgumentException("Named data slot already added");
289 slot = AllocateDataSlot ();
291 datastorehash.Add (name, slot);
297 public static void FreeNamedDataSlot (string name) {
298 lock (datastore_lock) {
299 if (datastorehash == null)
300 InitDataStoreHash ();
301 LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
304 datastorehash.Remove (slot);
309 public static LocalDataStoreSlot AllocateDataSlot () {
310 return new LocalDataStoreSlot (true);
313 public static object GetData (LocalDataStoreSlot slot) {
314 object[] slots = local_slots;
316 throw new ArgumentNullException ("slot");
317 if (slots != null && slot.slot < slots.Length)
318 return slots [slot.slot];
322 public static void SetData (LocalDataStoreSlot slot, object data) {
323 object[] slots = local_slots;
325 throw new ArgumentNullException ("slot");
327 slots = new object [slot.slot + 2];
329 } else if (slot.slot >= slots.Length) {
330 object[] nslots = new object [slot.slot + 2];
331 slots.CopyTo (nslots, 0);
335 slots [slot.slot] = data;
338 [MethodImplAttribute (MethodImplOptions.InternalCall)]
339 internal extern static void FreeLocalSlotValues (int slot, bool thread_local);
341 public static LocalDataStoreSlot GetNamedDataSlot(string name) {
342 lock (datastore_lock) {
343 if (datastorehash == null)
344 InitDataStoreHash ();
345 LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
348 slot=AllocateNamedDataSlot(name);
356 public static AppDomain GetDomain() {
357 return AppDomain.CurrentDomain;
360 [MethodImplAttribute(MethodImplOptions.InternalCall)]
361 public extern static int GetDomainID();
363 [MethodImplAttribute(MethodImplOptions.InternalCall)]
364 private extern static void ResetAbort_internal();
366 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
367 public static void ResetAbort ()
369 ResetAbort_internal ();
372 [MethodImplAttribute(MethodImplOptions.InternalCall)]
373 private extern static void Sleep_internal(int ms);
375 public static void Sleep (int millisecondsTimeout)
377 if (millisecondsTimeout < Timeout.Infinite)
378 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
380 Sleep_internal (millisecondsTimeout);
383 public static void Sleep (TimeSpan timeout)
385 long ms = (long) timeout.TotalMilliseconds;
386 if (ms < Timeout.Infinite || ms > Int32.MaxValue)
387 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
389 Sleep_internal ((int) ms);
392 // Returns the system thread handle
393 [MethodImplAttribute(MethodImplOptions.InternalCall)]
394 private extern IntPtr Thread_internal (MulticastDelegate start);
396 public Thread(ThreadStart start) {
398 throw new ArgumentNullException("Null ThreadStart");
403 private Thread (InternalThread it) {
404 internal_thread = it;
408 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
409 public ApartmentState ApartmentState {
411 if ((ThreadState & ThreadState.Stopped) != 0)
412 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
414 return (ApartmentState)Internal.apartment_state;
418 TrySetApartmentState (value);
423 //[MethodImplAttribute (MethodImplOptions.InternalCall)]
424 //private static extern int current_lcid ();
426 [MethodImplAttribute (MethodImplOptions.InternalCall)]
427 private extern static CultureInfo GetCachedCurrentCulture (InternalThread thread);
429 [MethodImplAttribute (MethodImplOptions.InternalCall)]
430 private extern void SetCachedCurrentCulture (CultureInfo culture);
432 [MethodImplAttribute (MethodImplOptions.InternalCall)]
433 private extern static CultureInfo GetCachedCurrentUICulture (InternalThread thread);
435 [MethodImplAttribute (MethodImplOptions.InternalCall)]
436 private extern void SetCachedCurrentUICulture (CultureInfo culture);
438 /* FIXME: in_currentculture exists once, but
439 culture_lock is once per appdomain. Is it correct
441 static object culture_lock = new object ();
444 * Thread objects are shared between appdomains, and CurrentCulture
445 * should always return an object in the calling appdomain. See bug
446 * http://bugzilla.ximian.com/show_bug.cgi?id=50049 for more info.
447 * This is hard to implement correctly and efficiently, so the current
448 * implementation is not perfect: changes made in one appdomain to the
449 * state of the current cultureinfo object are not visible to other
452 public CultureInfo CurrentCulture {
454 if (Internal.in_currentculture)
456 return CultureInfo.InvariantCulture;
458 CultureInfo culture = GetCachedCurrentCulture (Internal);
462 byte[] arr = ByteArrayToCurrentDomain (Internal.serialized_culture_info);
464 lock (culture_lock) {
465 Internal.in_currentculture=true;
466 culture = CultureInfo.ConstructCurrentCulture ();
468 // Don't serialize the culture in this case to avoid
469 // initializing the serialization infrastructure in the
470 // common case when the culture is not set explicitly.
472 SetCachedCurrentCulture (culture);
473 Internal.in_currentculture = false;
474 NumberFormatter.SetThreadCurrentCulture (culture);
480 * No cultureinfo object exists for this domain, so create one
481 * by deserializing the serialized form.
483 Internal.in_currentculture = true;
485 BinaryFormatter bf = new BinaryFormatter ();
486 MemoryStream ms = new MemoryStream (arr);
487 culture = (CultureInfo)bf.Deserialize (ms);
488 SetCachedCurrentCulture (culture);
490 Internal.in_currentculture = false;
493 NumberFormatter.SetThreadCurrentCulture (culture);
497 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
500 throw new ArgumentNullException ("value");
502 CultureInfo culture = GetCachedCurrentCulture (Internal);
503 if (culture == value)
506 value.CheckNeutral ();
507 Internal.in_currentculture = true;
509 SetCachedCurrentCulture (value);
511 byte[] serialized_form = null;
513 if (value.IsReadOnly && value.cached_serialized_form != null) {
514 serialized_form = value.cached_serialized_form;
516 BinaryFormatter bf = new BinaryFormatter();
517 MemoryStream ms = new MemoryStream ();
518 bf.Serialize (ms, value);
520 serialized_form = ms.GetBuffer ();
521 if (value.IsReadOnly)
522 value.cached_serialized_form = serialized_form;
525 Internal.serialized_culture_info = ByteArrayToRootDomain (serialized_form);
527 Internal.in_currentculture = false;
529 NumberFormatter.SetThreadCurrentCulture (value);
533 public CultureInfo CurrentUICulture {
535 if (Internal.in_currentculture)
537 return CultureInfo.InvariantCulture;
539 CultureInfo culture = GetCachedCurrentUICulture (Internal);
543 byte[] arr = ByteArrayToCurrentDomain (Internal.serialized_ui_culture_info);
545 lock (culture_lock) {
546 Internal.in_currentculture=true;
553 culture = CultureInfo.ConstructCurrentUICulture ();
555 // Don't serialize the culture in this case to avoid
556 // initializing the serialization infrastructure in the
557 // common case when the culture is not set explicitly.
559 SetCachedCurrentUICulture (culture);
560 Internal.in_currentculture = false;
566 * No cultureinfo object exists for this domain, so create one
567 * by deserializing the serialized form.
569 Internal.in_currentculture = true;
571 BinaryFormatter bf = new BinaryFormatter ();
572 MemoryStream ms = new MemoryStream (arr);
573 culture = (CultureInfo)bf.Deserialize (ms);
574 SetCachedCurrentUICulture (culture);
577 Internal.in_currentculture = false;
585 throw new ArgumentNullException ("value");
587 CultureInfo culture = GetCachedCurrentUICulture (Internal);
588 if (culture == value)
591 Internal.in_currentculture = true;
593 SetCachedCurrentUICulture (value);
595 byte[] serialized_form = null;
597 if (value.IsReadOnly && value.cached_serialized_form != null) {
598 serialized_form = value.cached_serialized_form;
600 BinaryFormatter bf = new BinaryFormatter();
601 MemoryStream ms = new MemoryStream ();
602 bf.Serialize (ms, value);
604 serialized_form = ms.GetBuffer ();
605 if (value.IsReadOnly)
606 value.cached_serialized_form = serialized_form;
609 Internal.serialized_ui_culture_info = ByteArrayToRootDomain (serialized_form);
611 Internal.in_currentculture = false;
616 public bool IsThreadPoolThread {
618 return IsThreadPoolThreadInternal;
622 internal bool IsThreadPoolThreadInternal {
624 return Internal.threadpool_thread;
627 Internal.threadpool_thread = value;
631 public bool IsAlive {
633 ThreadState curstate = GetState (Internal);
635 if((curstate & ThreadState.Aborted) != 0 ||
636 (curstate & ThreadState.Stopped) != 0 ||
637 (curstate & ThreadState.Unstarted) != 0) {
645 public bool IsBackground {
647 ThreadState thread_state = GetState (Internal);
648 if ((thread_state & ThreadState.Stopped) != 0)
649 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
651 return (thread_state & ThreadState.Background) != 0;
656 SetState (Internal, ThreadState.Background);
658 ClrState (Internal, ThreadState.Background);
663 [MethodImplAttribute(MethodImplOptions.InternalCall)]
664 private extern static string GetName_internal (InternalThread thread);
666 [MethodImplAttribute(MethodImplOptions.InternalCall)]
667 private extern static void SetName_internal (InternalThread thread, String name);
670 * The thread name must be shared by appdomains, so it is stored in
676 return GetName_internal (Internal);
680 SetName_internal (Internal, value);
685 public ThreadPriority Priority {
687 return(ThreadPriority.Lowest);
691 // FIXME: Implement setter.
696 public ThreadState ThreadState {
698 return GetState (Internal);
702 [MethodImplAttribute(MethodImplOptions.InternalCall)]
703 private extern static void Abort_internal (InternalThread thread, object stateInfo);
705 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
708 Abort_internal (Internal, null);
712 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
713 public void Abort (object stateInfo)
715 Abort_internal (Internal, stateInfo);
718 [MethodImplAttribute(MethodImplOptions.InternalCall)]
719 internal extern object GetAbortExceptionState ();
721 [MethodImplAttribute (MethodImplOptions.InternalCall)]
722 private extern static void Interrupt_internal (InternalThread thread);
724 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
725 public void Interrupt ()
727 Interrupt_internal (Internal);
731 // The current thread joins with 'this'. Set ms to 0 to block
732 // until this actually exits.
733 [MethodImplAttribute(MethodImplOptions.InternalCall)]
734 private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
738 Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
741 public bool Join(int millisecondsTimeout)
743 if (millisecondsTimeout < Timeout.Infinite)
744 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
746 return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
750 public bool Join(TimeSpan timeout)
752 long ms = (long) timeout.TotalMilliseconds;
753 if (ms < Timeout.Infinite || ms > Int32.MaxValue)
754 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
756 return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
761 [MethodImplAttribute(MethodImplOptions.InternalCall)]
762 public extern static void MemoryBarrier ();
766 [MethodImplAttribute(MethodImplOptions.InternalCall)]
767 private extern void Resume_internal();
770 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
771 public void Resume ()
777 [MethodImplAttribute (MethodImplOptions.InternalCall)]
778 private extern static void SpinWait_nop ();
781 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
782 public static void SpinWait (int iterations)
786 while (iterations-- > 0)
793 private void StartSafe ()
795 current_thread = this;
798 if (threadstart is ThreadStart) {
799 ((ThreadStart) threadstart) ();
801 ((ParameterizedThreadStart) threadstart) (start_obj);
803 } catch (ThreadAbortException) {
805 } catch (Exception ex) {
806 MoonlightUnhandledException (ex);
810 static MethodInfo moonlight_unhandled_exception = null;
812 static internal void MoonlightUnhandledException (Exception e)
815 if (moonlight_unhandled_exception == null) {
816 var assembly = System.Reflection.Assembly.Load ("System.Windows, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e");
817 var application = assembly.GetType ("System.Windows.Application");
818 moonlight_unhandled_exception = application.GetMethod ("OnUnhandledException",
819 System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
821 moonlight_unhandled_exception.Invoke (null, new object [] { null, e });
825 Console.WriteLine ("Unexpected exception while trying to report unhandled application exception: {0}", e);
832 private void StartUnsafe ()
834 current_thread = this;
836 if (threadstart is ThreadStart) {
837 ((ThreadStart) threadstart) ();
839 ((ParameterizedThreadStart) threadstart) (start_obj);
843 public void Start() {
844 // propagate informations from the original thread to the new thread
845 if (!ExecutionContext.IsFlowSuppressed ())
846 ec_to_set = ExecutionContext.Capture ();
847 Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
849 // Thread_internal creates and starts the new thread,
851 if (Thread_internal((ThreadStart) StartSafe) == (IntPtr) 0)
853 if (Thread_internal((ThreadStart) StartUnsafe) == (IntPtr) 0)
855 throw new SystemException ("Thread creation failed.");
859 [MethodImplAttribute(MethodImplOptions.InternalCall)]
860 private extern static void Suspend_internal(InternalThread thread);
863 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
864 public void Suspend ()
866 Suspend_internal (Internal);
870 [MethodImplAttribute (MethodImplOptions.InternalCall)]
871 extern private static void SetState (InternalThread thread, ThreadState set);
873 [MethodImplAttribute (MethodImplOptions.InternalCall)]
874 extern private static void ClrState (InternalThread thread, ThreadState clr);
876 [MethodImplAttribute (MethodImplOptions.InternalCall)]
877 extern private static ThreadState GetState (InternalThread thread);
881 [MethodImplAttribute (MethodImplOptions.InternalCall)]
882 extern public static byte VolatileRead (ref byte address);
884 [MethodImplAttribute (MethodImplOptions.InternalCall)]
885 extern public static double VolatileRead (ref double address);
887 [MethodImplAttribute (MethodImplOptions.InternalCall)]
888 extern public static short VolatileRead (ref short address);
890 [MethodImplAttribute (MethodImplOptions.InternalCall)]
891 extern public static int VolatileRead (ref int address);
893 [MethodImplAttribute (MethodImplOptions.InternalCall)]
894 extern public static long VolatileRead (ref long address);
896 [MethodImplAttribute (MethodImplOptions.InternalCall)]
897 extern public static IntPtr VolatileRead (ref IntPtr address);
899 [MethodImplAttribute (MethodImplOptions.InternalCall)]
900 extern public static object VolatileRead (ref object address);
902 [CLSCompliant(false)]
903 [MethodImplAttribute (MethodImplOptions.InternalCall)]
904 extern public static sbyte VolatileRead (ref sbyte address);
906 [MethodImplAttribute (MethodImplOptions.InternalCall)]
907 extern public static float VolatileRead (ref float address);
909 [CLSCompliant (false)]
910 [MethodImplAttribute (MethodImplOptions.InternalCall)]
911 extern public static ushort VolatileRead (ref ushort address);
913 [CLSCompliant (false)]
914 [MethodImplAttribute (MethodImplOptions.InternalCall)]
915 extern public static uint VolatileRead (ref uint address);
917 [CLSCompliant (false)]
918 [MethodImplAttribute (MethodImplOptions.InternalCall)]
919 extern public static ulong VolatileRead (ref ulong address);
921 [CLSCompliant (false)]
922 [MethodImplAttribute (MethodImplOptions.InternalCall)]
923 extern public static UIntPtr VolatileRead (ref UIntPtr address);
925 [MethodImplAttribute (MethodImplOptions.InternalCall)]
926 extern public static void VolatileWrite (ref byte address, byte value);
928 [MethodImplAttribute (MethodImplOptions.InternalCall)]
929 extern public static void VolatileWrite (ref double address, double value);
931 [MethodImplAttribute (MethodImplOptions.InternalCall)]
932 extern public static void VolatileWrite (ref short address, short value);
934 [MethodImplAttribute (MethodImplOptions.InternalCall)]
935 extern public static void VolatileWrite (ref int address, int value);
937 [MethodImplAttribute (MethodImplOptions.InternalCall)]
938 extern public static void VolatileWrite (ref long address, long value);
940 [MethodImplAttribute (MethodImplOptions.InternalCall)]
941 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
943 [MethodImplAttribute (MethodImplOptions.InternalCall)]
944 extern public static void VolatileWrite (ref object address, object value);
946 [CLSCompliant(false)]
947 [MethodImplAttribute (MethodImplOptions.InternalCall)]
948 extern public static void VolatileWrite (ref sbyte address, sbyte value);
950 [MethodImplAttribute (MethodImplOptions.InternalCall)]
951 extern public static void VolatileWrite (ref float address, float value);
953 [CLSCompliant (false)]
954 [MethodImplAttribute (MethodImplOptions.InternalCall)]
955 extern public static void VolatileWrite (ref ushort address, ushort value);
957 [CLSCompliant (false)]
958 [MethodImplAttribute (MethodImplOptions.InternalCall)]
959 extern public static void VolatileWrite (ref uint address, uint value);
961 [CLSCompliant (false)]
962 [MethodImplAttribute (MethodImplOptions.InternalCall)]
963 extern public static void VolatileWrite (ref ulong address, ulong value);
965 [CLSCompliant (false)]
966 [MethodImplAttribute (MethodImplOptions.InternalCall)]
967 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
971 private static int GetNewManagedId() {
972 return Interlocked.Increment(ref _managed_id_counter);
975 public Thread (ThreadStart start, int maxStackSize)
978 throw new ArgumentNullException ("start");
979 if (maxStackSize < 131072)
980 throw new ArgumentException ("< 128 kb", "maxStackSize");
983 Internal.stack_size = maxStackSize;
986 public Thread (ParameterizedThreadStart start)
989 throw new ArgumentNullException ("start");
994 public Thread (ParameterizedThreadStart start, int maxStackSize)
997 throw new ArgumentNullException ("start");
998 if (maxStackSize < 131072)
999 throw new ArgumentException ("< 128 kb", "maxStackSize");
1001 threadstart = start;
1002 Internal.stack_size = maxStackSize;
1005 [MonoTODO ("limited to CompressedStack support")]
1006 public ExecutionContext ExecutionContext {
1007 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
1010 _ec = new ExecutionContext ();
1015 public int ManagedThreadId {
1016 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
1018 if (Internal.managed_id == 0) {
1019 int new_managed_id = GetNewManagedId ();
1021 Interlocked.CompareExchange (ref Internal.managed_id, new_managed_id, 0);
1024 return Internal.managed_id;
1028 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
1029 public static void BeginCriticalRegion ()
1031 CurrentThread.Internal.critical_region_level++;
1034 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1035 public static void EndCriticalRegion ()
1037 CurrentThread.Internal.critical_region_level--;
1040 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1041 public static void BeginThreadAffinity ()
1043 // Managed and native threads are currently bound together.
1046 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1047 public static void EndThreadAffinity ()
1049 // Managed and native threads are currently bound together.
1053 public ApartmentState GetApartmentState ()
1055 return (ApartmentState)Internal.apartment_state;
1058 public void SetApartmentState (ApartmentState state)
1060 if (!TrySetApartmentState (state))
1061 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
1064 public bool TrySetApartmentState (ApartmentState state)
1066 /* Only throw this exception when changing the
1067 * state of another thread. See bug 324338
1069 if ((this != CurrentThread) &&
1070 (ThreadState & ThreadState.Unstarted) == 0)
1071 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
1073 if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown)
1076 Internal.apartment_state = (byte)state;
1082 [ComVisible (false)]
1083 public override int GetHashCode ()
1085 return ManagedThreadId;
1088 public void Start (object parameter)
1090 start_obj = parameter;
1095 // NOTE: This method doesn't show in the class library status page because
1096 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
1098 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
1099 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
1100 [Obsolete ("see CompressedStack class")]
1106 CompressedStack GetCompressedStack ()
1108 // Note: returns null if no CompressedStack has been set.
1109 // However CompressedStack.GetCompressedStack returns an
1110 // (empty?) CompressedStack instance.
1111 CompressedStack cs = ExecutionContext.SecurityContext.CompressedStack;
1112 return ((cs == null) || cs.IsEmpty ()) ? null : cs.CreateCopy ();
1115 // NOTE: This method doesn't show in the class library status page because
1116 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
1118 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
1119 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
1120 [Obsolete ("see CompressedStack class")]
1126 void SetCompressedStack (CompressedStack stack)
1128 ExecutionContext.SecurityContext.CompressedStack = stack;
1134 void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1136 throw new NotImplementedException ();
1139 void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1141 throw new NotImplementedException ();
1144 void _Thread.GetTypeInfoCount (out uint pcTInfo)
1146 throw new NotImplementedException ();
1149 void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1150 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1152 throw new NotImplementedException ();