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 #if NET_4_0 || BOOTSTRAP_NET_4_0
373 [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
374 [MethodImplAttribute(MethodImplOptions.InternalCall)]
375 public extern static bool Yield ();
379 [MethodImplAttribute(MethodImplOptions.InternalCall)]
380 private extern static void Sleep_internal(int ms);
382 public static void Sleep (int millisecondsTimeout)
384 if (millisecondsTimeout < Timeout.Infinite)
385 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
387 Sleep_internal (millisecondsTimeout);
390 public static void Sleep (TimeSpan timeout)
392 long ms = (long) timeout.TotalMilliseconds;
393 if (ms < Timeout.Infinite || ms > Int32.MaxValue)
394 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
396 Sleep_internal ((int) ms);
399 // Returns the system thread handle
400 [MethodImplAttribute(MethodImplOptions.InternalCall)]
401 private extern IntPtr Thread_internal (MulticastDelegate start);
403 public Thread(ThreadStart start) {
405 throw new ArgumentNullException("Null ThreadStart");
410 private Thread (InternalThread it) {
411 internal_thread = it;
415 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
416 public ApartmentState ApartmentState {
418 if ((ThreadState & ThreadState.Stopped) != 0)
419 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
421 return (ApartmentState)Internal.apartment_state;
425 TrySetApartmentState (value);
430 //[MethodImplAttribute (MethodImplOptions.InternalCall)]
431 //private static extern int current_lcid ();
433 [MethodImplAttribute (MethodImplOptions.InternalCall)]
434 private extern static CultureInfo GetCachedCurrentCulture (InternalThread thread);
436 [MethodImplAttribute (MethodImplOptions.InternalCall)]
437 private extern void SetCachedCurrentCulture (CultureInfo culture);
439 [MethodImplAttribute (MethodImplOptions.InternalCall)]
440 private extern static CultureInfo GetCachedCurrentUICulture (InternalThread thread);
442 [MethodImplAttribute (MethodImplOptions.InternalCall)]
443 private extern void SetCachedCurrentUICulture (CultureInfo culture);
445 /* FIXME: in_currentculture exists once, but
446 culture_lock is once per appdomain. Is it correct
448 static object culture_lock = new object ();
451 * Thread objects are shared between appdomains, and CurrentCulture
452 * should always return an object in the calling appdomain. See bug
453 * http://bugzilla.ximian.com/show_bug.cgi?id=50049 for more info.
454 * This is hard to implement correctly and efficiently, so the current
455 * implementation is not perfect: changes made in one appdomain to the
456 * state of the current cultureinfo object are not visible to other
459 public CultureInfo CurrentCulture {
461 if (Internal.in_currentculture)
463 return CultureInfo.InvariantCulture;
465 CultureInfo culture = GetCachedCurrentCulture (Internal);
469 byte[] arr = ByteArrayToCurrentDomain (Internal.serialized_culture_info);
471 lock (culture_lock) {
472 Internal.in_currentculture=true;
473 culture = CultureInfo.ConstructCurrentCulture ();
475 // Don't serialize the culture in this case to avoid
476 // initializing the serialization infrastructure in the
477 // common case when the culture is not set explicitly.
479 SetCachedCurrentCulture (culture);
480 Internal.in_currentculture = false;
481 NumberFormatter.SetThreadCurrentCulture (culture);
487 * No cultureinfo object exists for this domain, so create one
488 * by deserializing the serialized form.
490 Internal.in_currentculture = true;
492 BinaryFormatter bf = new BinaryFormatter ();
493 MemoryStream ms = new MemoryStream (arr);
494 culture = (CultureInfo)bf.Deserialize (ms);
495 SetCachedCurrentCulture (culture);
497 Internal.in_currentculture = false;
500 NumberFormatter.SetThreadCurrentCulture (culture);
504 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
507 throw new ArgumentNullException ("value");
509 CultureInfo culture = GetCachedCurrentCulture (Internal);
510 if (culture == value)
513 value.CheckNeutral ();
514 Internal.in_currentculture = true;
516 SetCachedCurrentCulture (value);
518 byte[] serialized_form = null;
520 if (value.IsReadOnly && value.cached_serialized_form != null) {
521 serialized_form = value.cached_serialized_form;
523 BinaryFormatter bf = new BinaryFormatter();
524 MemoryStream ms = new MemoryStream ();
525 bf.Serialize (ms, value);
527 serialized_form = ms.GetBuffer ();
528 if (value.IsReadOnly)
529 value.cached_serialized_form = serialized_form;
532 Internal.serialized_culture_info = ByteArrayToRootDomain (serialized_form);
534 Internal.in_currentculture = false;
536 NumberFormatter.SetThreadCurrentCulture (value);
540 public CultureInfo CurrentUICulture {
542 if (Internal.in_currentculture)
544 return CultureInfo.InvariantCulture;
546 CultureInfo culture = GetCachedCurrentUICulture (Internal);
550 byte[] arr = ByteArrayToCurrentDomain (Internal.serialized_ui_culture_info);
552 lock (culture_lock) {
553 Internal.in_currentculture=true;
560 culture = CultureInfo.ConstructCurrentUICulture ();
562 // Don't serialize the culture in this case to avoid
563 // initializing the serialization infrastructure in the
564 // common case when the culture is not set explicitly.
566 SetCachedCurrentUICulture (culture);
567 Internal.in_currentculture = false;
573 * No cultureinfo object exists for this domain, so create one
574 * by deserializing the serialized form.
576 Internal.in_currentculture = true;
578 BinaryFormatter bf = new BinaryFormatter ();
579 MemoryStream ms = new MemoryStream (arr);
580 culture = (CultureInfo)bf.Deserialize (ms);
581 SetCachedCurrentUICulture (culture);
584 Internal.in_currentculture = false;
592 throw new ArgumentNullException ("value");
594 CultureInfo culture = GetCachedCurrentUICulture (Internal);
595 if (culture == value)
598 Internal.in_currentculture = true;
600 SetCachedCurrentUICulture (value);
602 byte[] serialized_form = null;
604 if (value.IsReadOnly && value.cached_serialized_form != null) {
605 serialized_form = value.cached_serialized_form;
607 BinaryFormatter bf = new BinaryFormatter();
608 MemoryStream ms = new MemoryStream ();
609 bf.Serialize (ms, value);
611 serialized_form = ms.GetBuffer ();
612 if (value.IsReadOnly)
613 value.cached_serialized_form = serialized_form;
616 Internal.serialized_ui_culture_info = ByteArrayToRootDomain (serialized_form);
618 Internal.in_currentculture = false;
623 public bool IsThreadPoolThread {
625 return IsThreadPoolThreadInternal;
629 internal bool IsThreadPoolThreadInternal {
631 return Internal.threadpool_thread;
634 Internal.threadpool_thread = value;
638 public bool IsAlive {
640 ThreadState curstate = GetState (Internal);
642 if((curstate & ThreadState.Aborted) != 0 ||
643 (curstate & ThreadState.Stopped) != 0 ||
644 (curstate & ThreadState.Unstarted) != 0) {
652 public bool IsBackground {
654 ThreadState thread_state = GetState (Internal);
655 if ((thread_state & ThreadState.Stopped) != 0)
656 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
658 return (thread_state & ThreadState.Background) != 0;
663 SetState (Internal, ThreadState.Background);
665 ClrState (Internal, ThreadState.Background);
670 [MethodImplAttribute(MethodImplOptions.InternalCall)]
671 private extern static string GetName_internal (InternalThread thread);
673 [MethodImplAttribute(MethodImplOptions.InternalCall)]
674 private extern static void SetName_internal (InternalThread thread, String name);
677 * The thread name must be shared by appdomains, so it is stored in
683 return GetName_internal (Internal);
687 SetName_internal (Internal, value);
692 public ThreadPriority Priority {
694 return(ThreadPriority.Lowest);
698 // FIXME: Implement setter.
703 public ThreadState ThreadState {
705 return GetState (Internal);
709 [MethodImplAttribute(MethodImplOptions.InternalCall)]
710 private extern static void Abort_internal (InternalThread thread, object stateInfo);
712 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
715 Abort_internal (Internal, null);
719 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
720 public void Abort (object stateInfo)
722 Abort_internal (Internal, stateInfo);
725 [MethodImplAttribute(MethodImplOptions.InternalCall)]
726 internal extern object GetAbortExceptionState ();
728 [MethodImplAttribute (MethodImplOptions.InternalCall)]
729 private extern static void Interrupt_internal (InternalThread thread);
731 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
732 public void Interrupt ()
734 Interrupt_internal (Internal);
738 // The current thread joins with 'this'. Set ms to 0 to block
739 // until this actually exits.
740 [MethodImplAttribute(MethodImplOptions.InternalCall)]
741 private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
745 Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
748 public bool Join(int millisecondsTimeout)
750 if (millisecondsTimeout < Timeout.Infinite)
751 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
753 return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
757 public bool Join(TimeSpan timeout)
759 long ms = (long) timeout.TotalMilliseconds;
760 if (ms < Timeout.Infinite || ms > Int32.MaxValue)
761 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
763 return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
768 [MethodImplAttribute(MethodImplOptions.InternalCall)]
769 public extern static void MemoryBarrier ();
773 [MethodImplAttribute(MethodImplOptions.InternalCall)]
774 private extern void Resume_internal();
777 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
778 public void Resume ()
784 [MethodImplAttribute (MethodImplOptions.InternalCall)]
785 private extern static void SpinWait_nop ();
788 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
789 public static void SpinWait (int iterations)
793 while (iterations-- > 0)
800 private void StartSafe ()
802 current_thread = this;
805 if (threadstart is ThreadStart) {
806 ((ThreadStart) threadstart) ();
808 ((ParameterizedThreadStart) threadstart) (start_obj);
810 } catch (ThreadAbortException) {
812 } catch (Exception ex) {
813 MoonlightUnhandledException (ex);
817 static MethodInfo moonlight_unhandled_exception = null;
819 static internal void MoonlightUnhandledException (Exception e)
822 if (moonlight_unhandled_exception == null) {
823 var assembly = System.Reflection.Assembly.Load ("System.Windows, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e");
824 var application = assembly.GetType ("System.Windows.Application");
825 moonlight_unhandled_exception = application.GetMethod ("OnUnhandledException",
826 System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
828 moonlight_unhandled_exception.Invoke (null, new object [] { null, e });
832 Console.WriteLine ("Unexpected exception while trying to report unhandled application exception: {0}", e);
839 private void StartUnsafe ()
841 current_thread = this;
843 if (threadstart is ThreadStart) {
844 ((ThreadStart) threadstart) ();
846 ((ParameterizedThreadStart) threadstart) (start_obj);
850 public void Start() {
851 // propagate informations from the original thread to the new thread
852 if (!ExecutionContext.IsFlowSuppressed ())
853 ec_to_set = ExecutionContext.Capture ();
854 Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
856 // Thread_internal creates and starts the new thread,
858 if (Thread_internal((ThreadStart) StartSafe) == (IntPtr) 0)
860 if (Thread_internal((ThreadStart) StartUnsafe) == (IntPtr) 0)
862 throw new SystemException ("Thread creation failed.");
866 [MethodImplAttribute(MethodImplOptions.InternalCall)]
867 private extern static void Suspend_internal(InternalThread thread);
870 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
871 public void Suspend ()
873 Suspend_internal (Internal);
877 [MethodImplAttribute (MethodImplOptions.InternalCall)]
878 extern private static void SetState (InternalThread thread, ThreadState set);
880 [MethodImplAttribute (MethodImplOptions.InternalCall)]
881 extern private static void ClrState (InternalThread thread, ThreadState clr);
883 [MethodImplAttribute (MethodImplOptions.InternalCall)]
884 extern private static ThreadState GetState (InternalThread thread);
888 [MethodImplAttribute (MethodImplOptions.InternalCall)]
889 extern public static byte VolatileRead (ref byte address);
891 [MethodImplAttribute (MethodImplOptions.InternalCall)]
892 extern public static double VolatileRead (ref double address);
894 [MethodImplAttribute (MethodImplOptions.InternalCall)]
895 extern public static short VolatileRead (ref short address);
897 [MethodImplAttribute (MethodImplOptions.InternalCall)]
898 extern public static int VolatileRead (ref int address);
900 [MethodImplAttribute (MethodImplOptions.InternalCall)]
901 extern public static long VolatileRead (ref long address);
903 [MethodImplAttribute (MethodImplOptions.InternalCall)]
904 extern public static IntPtr VolatileRead (ref IntPtr address);
906 [MethodImplAttribute (MethodImplOptions.InternalCall)]
907 extern public static object VolatileRead (ref object address);
909 [CLSCompliant(false)]
910 [MethodImplAttribute (MethodImplOptions.InternalCall)]
911 extern public static sbyte VolatileRead (ref sbyte address);
913 [MethodImplAttribute (MethodImplOptions.InternalCall)]
914 extern public static float VolatileRead (ref float address);
916 [CLSCompliant (false)]
917 [MethodImplAttribute (MethodImplOptions.InternalCall)]
918 extern public static ushort VolatileRead (ref ushort address);
920 [CLSCompliant (false)]
921 [MethodImplAttribute (MethodImplOptions.InternalCall)]
922 extern public static uint VolatileRead (ref uint address);
924 [CLSCompliant (false)]
925 [MethodImplAttribute (MethodImplOptions.InternalCall)]
926 extern public static ulong VolatileRead (ref ulong address);
928 [CLSCompliant (false)]
929 [MethodImplAttribute (MethodImplOptions.InternalCall)]
930 extern public static UIntPtr VolatileRead (ref UIntPtr address);
932 [MethodImplAttribute (MethodImplOptions.InternalCall)]
933 extern public static void VolatileWrite (ref byte address, byte value);
935 [MethodImplAttribute (MethodImplOptions.InternalCall)]
936 extern public static void VolatileWrite (ref double address, double value);
938 [MethodImplAttribute (MethodImplOptions.InternalCall)]
939 extern public static void VolatileWrite (ref short address, short value);
941 [MethodImplAttribute (MethodImplOptions.InternalCall)]
942 extern public static void VolatileWrite (ref int address, int value);
944 [MethodImplAttribute (MethodImplOptions.InternalCall)]
945 extern public static void VolatileWrite (ref long address, long value);
947 [MethodImplAttribute (MethodImplOptions.InternalCall)]
948 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
950 [MethodImplAttribute (MethodImplOptions.InternalCall)]
951 extern public static void VolatileWrite (ref object address, object value);
953 [CLSCompliant(false)]
954 [MethodImplAttribute (MethodImplOptions.InternalCall)]
955 extern public static void VolatileWrite (ref sbyte address, sbyte value);
957 [MethodImplAttribute (MethodImplOptions.InternalCall)]
958 extern public static void VolatileWrite (ref float address, float value);
960 [CLSCompliant (false)]
961 [MethodImplAttribute (MethodImplOptions.InternalCall)]
962 extern public static void VolatileWrite (ref ushort address, ushort value);
964 [CLSCompliant (false)]
965 [MethodImplAttribute (MethodImplOptions.InternalCall)]
966 extern public static void VolatileWrite (ref uint address, uint value);
968 [CLSCompliant (false)]
969 [MethodImplAttribute (MethodImplOptions.InternalCall)]
970 extern public static void VolatileWrite (ref ulong address, ulong value);
972 [CLSCompliant (false)]
973 [MethodImplAttribute (MethodImplOptions.InternalCall)]
974 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
978 private static int GetNewManagedId() {
979 return Interlocked.Increment(ref _managed_id_counter);
982 public Thread (ThreadStart start, int maxStackSize)
985 throw new ArgumentNullException ("start");
986 if (maxStackSize < 131072)
987 throw new ArgumentException ("< 128 kb", "maxStackSize");
990 Internal.stack_size = maxStackSize;
993 public Thread (ParameterizedThreadStart start)
996 throw new ArgumentNullException ("start");
1001 public Thread (ParameterizedThreadStart start, int maxStackSize)
1004 throw new ArgumentNullException ("start");
1005 if (maxStackSize < 131072)
1006 throw new ArgumentException ("< 128 kb", "maxStackSize");
1008 threadstart = start;
1009 Internal.stack_size = maxStackSize;
1012 [MonoTODO ("limited to CompressedStack support")]
1013 public ExecutionContext ExecutionContext {
1014 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
1017 _ec = new ExecutionContext ();
1022 public int ManagedThreadId {
1023 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
1026 if (internal_thread != null && internal_thread.managed_id != 0)
1027 return internal_thread.managed_id;
1029 if (Internal.managed_id == 0) {
1030 int new_managed_id = GetNewManagedId ();
1032 Interlocked.CompareExchange (ref Internal.managed_id, new_managed_id, 0);
1035 return Internal.managed_id;
1039 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
1040 public static void BeginCriticalRegion ()
1042 CurrentThread.Internal.critical_region_level++;
1045 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1046 public static void EndCriticalRegion ()
1048 CurrentThread.Internal.critical_region_level--;
1051 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1052 public static void BeginThreadAffinity ()
1054 // Managed and native threads are currently bound together.
1057 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1058 public static void EndThreadAffinity ()
1060 // Managed and native threads are currently bound together.
1064 public ApartmentState GetApartmentState ()
1066 return (ApartmentState)Internal.apartment_state;
1069 public void SetApartmentState (ApartmentState state)
1071 if (!TrySetApartmentState (state))
1072 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
1075 public bool TrySetApartmentState (ApartmentState state)
1077 /* Only throw this exception when changing the
1078 * state of another thread. See bug 324338
1080 if ((this != CurrentThread) &&
1081 (ThreadState & ThreadState.Unstarted) == 0)
1082 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
1084 if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown)
1087 Internal.apartment_state = (byte)state;
1093 [ComVisible (false)]
1094 public override int GetHashCode ()
1096 return ManagedThreadId;
1099 public void Start (object parameter)
1101 start_obj = parameter;
1106 // NOTE: This method doesn't show in the class library status page because
1107 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
1109 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
1110 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
1111 [Obsolete ("see CompressedStack class")]
1117 CompressedStack GetCompressedStack ()
1119 // Note: returns null if no CompressedStack has been set.
1120 // However CompressedStack.GetCompressedStack returns an
1121 // (empty?) CompressedStack instance.
1122 CompressedStack cs = ExecutionContext.SecurityContext.CompressedStack;
1123 return ((cs == null) || cs.IsEmpty ()) ? null : cs.CreateCopy ();
1126 // NOTE: This method doesn't show in the class library status page because
1127 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
1129 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
1130 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
1131 [Obsolete ("see CompressedStack class")]
1137 void SetCompressedStack (CompressedStack stack)
1139 ExecutionContext.SecurityContext.CompressedStack = stack;
1145 void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1147 throw new NotImplementedException ();
1150 void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1152 throw new NotImplementedException ();
1155 void _Thread.GetTypeInfoCount (out uint pcTInfo)
1157 throw new NotImplementedException ();
1160 void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1161 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1163 throw new NotImplementedException ();