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.Generic;
40 using System.Reflection;
41 using System.Security;
42 using System.Runtime.ConstrainedExecution;
44 namespace System.Threading {
45 [StructLayout (LayoutKind.Sequential)]
46 sealed 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 /* accessed only from unmanaged code */
58 private ThreadState state;
59 private object abort_exc;
60 private int abort_state_handle;
61 /* thread_id is only accessed from unmanaged code */
62 internal Int64 thread_id;
64 /* start_notify is used by the runtime to signal that Start()
67 private IntPtr start_notify;
68 private IntPtr stack_ptr;
69 private UIntPtr static_data; /* GC-tracked */
70 private IntPtr runtime_thread_info;
71 /* current System.Runtime.Remoting.Contexts.Context instance
72 keep as an object to avoid triggering its class constructor when not needed */
73 private object current_appcontext;
74 private object pending_exception;
75 private object root_domain_thread;
76 internal byte[] _serialized_principal;
77 internal int _serialized_principal_version;
78 private IntPtr appdomain_refs;
79 private int interruption_requested;
80 private IntPtr synch_cs;
81 internal bool threadpool_thread;
82 private bool thread_interrupt_requested;
83 /* These are used from managed code */
84 internal int stack_size;
85 internal byte apartment_state;
86 internal volatile int critical_region_level;
87 internal int managed_id;
89 private IntPtr manage_callback;
90 private IntPtr interrupt_on_stop;
92 private IntPtr thread_pinning_ref;
93 private IntPtr async_invoke_method;
95 * These fields are used to avoid having to increment corlib versions
96 * when a new field is added to the unmanaged MonoThread structure.
98 private IntPtr unused1;
99 private IntPtr unused2;
101 #pragma warning restore 169, 414, 649
103 // Closes the system thread handle
104 [MethodImplAttribute(MethodImplOptions.InternalCall)]
105 private extern void Thread_free_internal(IntPtr handle);
107 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
109 Thread_free_internal(system_thread_handle);
113 [StructLayout (LayoutKind.Sequential)]
114 public sealed partial class Thread {
115 #pragma warning disable 414
116 #region Sync with metadata/object-internals.h
117 private InternalThread internal_thread;
118 object m_ThreadStartArg;
119 private ExecutionContext ec_to_set;
121 #pragma warning restore 414
123 IPrincipal principal;
124 int principal_version;
125 bool current_culture_set;
126 bool current_ui_culture_set;
127 CultureInfo current_culture;
128 CultureInfo current_ui_culture;
130 // the name of local_slots, current_thread and _ec is
131 // important because they are used by the runtime.
133 static object[] local_slots;
136 static Thread current_thread;
138 /* The actual ExecutionContext of the thread. It's
139 ThreadStatic so that it's not shared between
142 static ExecutionContext _ec;
144 static NamedDataSlot namedDataSlot;
146 static internal CultureInfo default_culture;
147 static internal CultureInfo default_ui_culture;
149 // can be both a ThreadStart and a ParameterizedThreadStart
150 private MulticastDelegate m_Delegate;
151 //private string thread_name=null;
153 [MethodImplAttribute(MethodImplOptions.InternalCall)]
154 private extern void ConstructInternalThread ();
156 private InternalThread Internal {
158 if (internal_thread == null)
159 ConstructInternalThread ();
160 return internal_thread;
164 public static Context CurrentContext {
165 [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
167 return(AppDomain.InternalGetContext ());
172 * These two methods return an array in the target
173 * domain with the same content as the argument. If
174 * the argument is already in the target domain, then
175 * the argument is returned, otherwise a copy.
177 [MethodImplAttribute(MethodImplOptions.InternalCall)]
178 private extern static byte[] ByteArrayToRootDomain (byte[] arr);
180 [MethodImplAttribute(MethodImplOptions.InternalCall)]
181 private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
183 static void DeserializePrincipal (Thread th)
185 MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
186 int type = ms.ReadByte ();
188 BinaryFormatter bf = new BinaryFormatter ();
189 th.principal = (IPrincipal) bf.Deserialize (ms);
190 th.principal_version = th.Internal._serialized_principal_version;
191 } else if (type == 1) {
192 BinaryReader reader = new BinaryReader (ms);
193 string name = reader.ReadString ();
194 string auth_type = reader.ReadString ();
195 int n_roles = reader.ReadInt32 ();
196 string [] roles = null;
198 roles = new string [n_roles];
199 for (int i = 0; i < n_roles; i++)
200 roles [i] = reader.ReadString ();
202 th.principal = new GenericPrincipal (new GenericIdentity (name, auth_type), roles);
203 } else if (type == 2 || type == 3) {
204 string [] roles = type == 2 ? null : new string [0];
205 th.principal = new GenericPrincipal (new GenericIdentity ("", ""), roles);
209 static void SerializePrincipal (Thread th, IPrincipal value)
211 MemoryStream ms = new MemoryStream ();
213 if (value.GetType () == typeof (GenericPrincipal)) {
214 GenericPrincipal gp = (GenericPrincipal) value;
215 if (gp.Identity != null && gp.Identity.GetType () == typeof (GenericIdentity)) {
216 GenericIdentity id = (GenericIdentity) gp.Identity;
217 if (id.Name == "" && id.AuthenticationType == "") {
218 if (gp.Roles == null) {
221 } else if (gp.Roles.Length == 0) {
227 BinaryWriter br = new BinaryWriter (ms);
228 br.Write (gp.Identity.Name);
229 br.Write (gp.Identity.AuthenticationType);
230 string [] roles = gp.Roles;
232 br.Write ((int) (-1));
234 br.Write (roles.Length);
235 foreach (string s in roles) {
246 BinaryFormatter bf = new BinaryFormatter ();
248 bf.Serialize (ms, value);
251 th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
254 public static IPrincipal CurrentPrincipal {
256 Thread th = CurrentThread;
258 if (th.principal_version != th.Internal._serialized_principal_version)
261 if (th.principal != null)
264 if (th.Internal._serialized_principal != null) {
266 DeserializePrincipal (th);
271 th.principal = GetDomain ().DefaultPrincipal;
272 th.principal_version = th.Internal._serialized_principal_version;
275 [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
277 Thread th = CurrentThread;
279 if (value != GetDomain ().DefaultPrincipal) {
280 ++th.Internal._serialized_principal_version;
282 SerializePrincipal (th, value);
283 } catch (Exception) {
284 th.Internal._serialized_principal = null;
286 th.principal_version = th.Internal._serialized_principal_version;
288 th.Internal._serialized_principal = null;
291 th.principal = value;
295 // Looks up the object associated with the current thread
296 // this is called by the JIT directly, too
297 [MethodImplAttribute(MethodImplOptions.InternalCall)]
298 private extern static InternalThread CurrentInternalThread_internal();
300 [MethodImplAttribute(MethodImplOptions.InternalCall)]
301 internal extern static uint AllocTlsData (Type type);
303 [MethodImplAttribute(MethodImplOptions.InternalCall)]
304 internal extern static void DestroyTlsData (uint offset);
306 public static Thread CurrentThread {
307 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
309 if (current_thread == null)
310 current_thread = new Thread (CurrentInternalThread_internal ());
311 return current_thread;
315 internal static int CurrentThreadId {
317 return (int)(CurrentThread.internal_thread.thread_id);
321 static NamedDataSlot NamedDataSlot {
323 if (namedDataSlot == null)
324 Interlocked.CompareExchange (ref namedDataSlot, new NamedDataSlot (true), null);
326 return namedDataSlot;
330 public static LocalDataStoreSlot AllocateNamedDataSlot (string name)
332 return NamedDataSlot.Allocate (name);
335 public static void FreeNamedDataSlot (string name)
337 NamedDataSlot.Free (name);
340 public static LocalDataStoreSlot AllocateDataSlot ()
342 return new LocalDataStoreSlot (true);
345 public static object GetData (LocalDataStoreSlot slot) {
346 object[] slots = local_slots;
348 throw new ArgumentNullException ("slot");
349 if (slots != null && slot.slot < slots.Length)
350 return slots [slot.slot];
354 public static void SetData (LocalDataStoreSlot slot, object data) {
355 object[] slots = local_slots;
357 throw new ArgumentNullException ("slot");
359 slots = new object [slot.slot + 2];
361 } else if (slot.slot >= slots.Length) {
362 object[] nslots = new object [slot.slot + 2];
363 slots.CopyTo (nslots, 0);
367 slots [slot.slot] = data;
370 [MethodImplAttribute (MethodImplOptions.InternalCall)]
371 internal extern static void FreeLocalSlotValues (int slot, bool thread_local);
373 public static LocalDataStoreSlot GetNamedDataSlot(string name)
375 return NamedDataSlot.Get (name);
378 public static AppDomain GetDomain() {
379 return AppDomain.CurrentDomain;
382 [MethodImplAttribute(MethodImplOptions.InternalCall)]
383 public extern static int GetDomainID();
385 [MethodImplAttribute(MethodImplOptions.InternalCall)]
386 private extern static void ResetAbort_internal();
388 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
389 public static void ResetAbort ()
391 ResetAbort_internal ();
394 [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
395 [MethodImplAttribute(MethodImplOptions.InternalCall)]
396 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
397 public extern static bool Yield ();
400 [MethodImplAttribute(MethodImplOptions.InternalCall)]
401 private extern static void Sleep_internal(int ms);
403 public static void Sleep (int millisecondsTimeout)
405 if (millisecondsTimeout < Timeout.Infinite)
406 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
408 Sleep_internal (millisecondsTimeout);
411 public static void Sleep (TimeSpan timeout)
413 long ms = (long) timeout.TotalMilliseconds;
414 if (ms < Timeout.Infinite || ms > Int32.MaxValue)
415 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
417 Sleep_internal ((int) ms);
420 // Returns the system thread handle
421 [MethodImplAttribute(MethodImplOptions.InternalCall)]
422 private extern IntPtr Thread_internal (MulticastDelegate start);
424 public Thread(ThreadStart start) {
426 throw new ArgumentNullException("Null ThreadStart");
431 private Thread (InternalThread it) {
432 internal_thread = it;
435 // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
436 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
441 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
442 public ApartmentState ApartmentState {
444 if ((ThreadState & ThreadState.Stopped) != 0)
445 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
447 return (ApartmentState)Internal.apartment_state;
451 TrySetApartmentState (value);
455 //[MethodImplAttribute (MethodImplOptions.InternalCall)]
456 //private static extern int current_lcid ();
458 public CultureInfo CurrentCulture {
460 CultureInfo culture = current_culture;
461 if (current_culture_set && culture != null)
464 if (default_culture != null)
465 return default_culture;
467 current_culture = culture = CultureInfo.ConstructCurrentCulture ();
471 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
474 throw new ArgumentNullException ("value");
476 value.CheckNeutral ();
477 current_culture = value;
478 current_culture_set = true;
482 public CultureInfo CurrentUICulture {
484 CultureInfo culture = current_ui_culture;
485 if (current_ui_culture_set && culture != null)
488 if (default_ui_culture != null)
489 return default_ui_culture;
491 current_ui_culture = culture = CultureInfo.ConstructCurrentUICulture ();
497 throw new ArgumentNullException ("value");
498 current_ui_culture = value;
499 current_ui_culture_set = true;
503 public bool IsThreadPoolThread {
505 return IsThreadPoolThreadInternal;
509 internal bool IsThreadPoolThreadInternal {
511 return Internal.threadpool_thread;
514 Internal.threadpool_thread = value;
518 public bool IsAlive {
520 ThreadState curstate = GetState (Internal);
522 if((curstate & ThreadState.Aborted) != 0 ||
523 (curstate & ThreadState.Stopped) != 0 ||
524 (curstate & ThreadState.Unstarted) != 0) {
532 public bool IsBackground {
534 ThreadState thread_state = GetState (Internal);
535 if ((thread_state & ThreadState.Stopped) != 0)
536 throw new ThreadStateException ("Thread is dead; state can not be accessed.");
538 return (thread_state & ThreadState.Background) != 0;
543 SetState (Internal, ThreadState.Background);
545 ClrState (Internal, ThreadState.Background);
550 [MethodImplAttribute(MethodImplOptions.InternalCall)]
551 private extern static string GetName_internal (InternalThread thread);
553 [MethodImplAttribute(MethodImplOptions.InternalCall)]
554 private extern static void SetName_internal (InternalThread thread, String name);
557 * The thread name must be shared by appdomains, so it is stored in
563 return GetName_internal (Internal);
567 SetName_internal (Internal, value);
571 public ThreadPriority Priority {
573 return (ThreadPriority)GetPriority (Internal);
577 // FIXME: This doesn't do anything yet
578 SetPriority (Internal, (int)value);
582 public ThreadState ThreadState {
584 return GetState (Internal);
588 [MethodImplAttribute(MethodImplOptions.InternalCall)]
589 private extern static void Abort_internal (InternalThread thread, object stateInfo);
591 [MethodImplAttribute(MethodImplOptions.InternalCall)]
592 private extern static int GetPriority (InternalThread thread);
594 [MethodImplAttribute(MethodImplOptions.InternalCall)]
595 private extern static void SetPriority (InternalThread thread, int priority);
597 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
600 Abort_internal (Internal, null);
603 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
604 public void Abort (object stateInfo)
606 Abort_internal (Internal, stateInfo);
609 [MethodImplAttribute(MethodImplOptions.InternalCall)]
610 extern object GetAbortExceptionState ();
612 internal object AbortReason {
614 return GetAbortExceptionState ();
618 [MethodImplAttribute (MethodImplOptions.InternalCall)]
619 private extern static void Interrupt_internal (InternalThread thread);
621 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
622 public void Interrupt ()
624 Interrupt_internal (Internal);
627 // The current thread joins with 'this'. Set ms to 0 to block
628 // until this actually exits.
629 [MethodImplAttribute(MethodImplOptions.InternalCall)]
630 private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
634 Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
637 public bool Join(int millisecondsTimeout)
639 if (millisecondsTimeout < Timeout.Infinite)
640 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
642 return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
645 public bool Join(TimeSpan timeout)
647 long ms = (long) timeout.TotalMilliseconds;
648 if (ms < Timeout.Infinite || ms > Int32.MaxValue)
649 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
651 return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
654 [MethodImplAttribute(MethodImplOptions.InternalCall)]
655 public extern static void MemoryBarrier ();
657 [MethodImplAttribute(MethodImplOptions.InternalCall)]
658 private extern void Resume_internal();
661 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
662 public void Resume ()
667 [MethodImplAttribute (MethodImplOptions.InternalCall)]
668 private extern static void SpinWait_nop ();
671 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
672 public static void SpinWait (int iterations)
676 while (iterations-- > 0)
682 private void StartInternal ()
684 current_thread = this;
686 if (m_Delegate is ThreadStart) {
687 ((ThreadStart) m_Delegate) ();
689 ((ParameterizedThreadStart) m_Delegate) (m_ThreadStartArg);
693 public void Start() {
694 // propagate informations from the original thread to the new thread
695 ec_to_set = ExecutionContext.Capture (false, true);
696 Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
698 // Thread_internal creates and starts the new thread,
699 if (Thread_internal((ThreadStart) StartInternal) == (IntPtr) 0)
700 throw new SystemException ("Thread creation failed.");
703 [MethodImplAttribute(MethodImplOptions.InternalCall)]
704 private extern static void Suspend_internal(InternalThread thread);
707 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
708 public void Suspend ()
710 Suspend_internal (Internal);
713 [MethodImplAttribute (MethodImplOptions.InternalCall)]
714 extern private static void SetState (InternalThread thread, ThreadState set);
716 [MethodImplAttribute (MethodImplOptions.InternalCall)]
717 extern private static void ClrState (InternalThread thread, ThreadState clr);
719 [MethodImplAttribute (MethodImplOptions.InternalCall)]
720 extern private static ThreadState GetState (InternalThread thread);
722 [MethodImplAttribute (MethodImplOptions.InternalCall)]
723 extern public static byte VolatileRead (ref byte address);
725 [MethodImplAttribute (MethodImplOptions.InternalCall)]
726 extern public static double VolatileRead (ref double address);
728 [MethodImplAttribute (MethodImplOptions.InternalCall)]
729 extern public static short VolatileRead (ref short address);
731 [MethodImplAttribute (MethodImplOptions.InternalCall)]
732 extern public static int VolatileRead (ref int address);
734 [MethodImplAttribute (MethodImplOptions.InternalCall)]
735 extern public static long VolatileRead (ref long address);
737 [MethodImplAttribute (MethodImplOptions.InternalCall)]
738 extern public static IntPtr VolatileRead (ref IntPtr address);
740 [MethodImplAttribute (MethodImplOptions.InternalCall)]
741 extern public static object VolatileRead (ref object address);
743 [CLSCompliant(false)]
744 [MethodImplAttribute (MethodImplOptions.InternalCall)]
745 extern public static sbyte VolatileRead (ref sbyte address);
747 [MethodImplAttribute (MethodImplOptions.InternalCall)]
748 extern public static float VolatileRead (ref float address);
750 [CLSCompliant (false)]
751 [MethodImplAttribute (MethodImplOptions.InternalCall)]
752 extern public static ushort VolatileRead (ref ushort address);
754 [CLSCompliant (false)]
755 [MethodImplAttribute (MethodImplOptions.InternalCall)]
756 extern public static uint VolatileRead (ref uint address);
758 [CLSCompliant (false)]
759 [MethodImplAttribute (MethodImplOptions.InternalCall)]
760 extern public static ulong VolatileRead (ref ulong address);
762 [CLSCompliant (false)]
763 [MethodImplAttribute (MethodImplOptions.InternalCall)]
764 extern public static UIntPtr VolatileRead (ref UIntPtr address);
766 [MethodImplAttribute (MethodImplOptions.InternalCall)]
767 extern public static void VolatileWrite (ref byte address, byte value);
769 [MethodImplAttribute (MethodImplOptions.InternalCall)]
770 extern public static void VolatileWrite (ref double address, double value);
772 [MethodImplAttribute (MethodImplOptions.InternalCall)]
773 extern public static void VolatileWrite (ref short address, short value);
775 [MethodImplAttribute (MethodImplOptions.InternalCall)]
776 extern public static void VolatileWrite (ref int address, int value);
778 [MethodImplAttribute (MethodImplOptions.InternalCall)]
779 extern public static void VolatileWrite (ref long address, long value);
781 [MethodImplAttribute (MethodImplOptions.InternalCall)]
782 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
784 [MethodImplAttribute (MethodImplOptions.InternalCall)]
785 extern public static void VolatileWrite (ref object address, object value);
787 [CLSCompliant(false)]
788 [MethodImplAttribute (MethodImplOptions.InternalCall)]
789 extern public static void VolatileWrite (ref sbyte address, sbyte value);
791 [MethodImplAttribute (MethodImplOptions.InternalCall)]
792 extern public static void VolatileWrite (ref float address, float value);
794 [CLSCompliant (false)]
795 [MethodImplAttribute (MethodImplOptions.InternalCall)]
796 extern public static void VolatileWrite (ref ushort address, ushort value);
798 [CLSCompliant (false)]
799 [MethodImplAttribute (MethodImplOptions.InternalCall)]
800 extern public static void VolatileWrite (ref uint address, uint value);
802 [CLSCompliant (false)]
803 [MethodImplAttribute (MethodImplOptions.InternalCall)]
804 extern public static void VolatileWrite (ref ulong address, ulong value);
806 [CLSCompliant (false)]
807 [MethodImplAttribute (MethodImplOptions.InternalCall)]
808 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
810 [MethodImplAttribute (MethodImplOptions.InternalCall)]
811 extern static int SystemMaxStackStize ();
813 static int GetProcessDefaultStackSize (int maxStackSize)
815 if (maxStackSize < 131072) // make sure stack is at least 128k big
818 int page_size = Environment.GetPageSize ();
820 if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
821 maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
823 /* Respect the max stack size imposed by the system*/
824 return Math.Min (maxStackSize, SystemMaxStackStize ());
827 void SetStart (MulticastDelegate start, int maxStackSize)
830 Internal.stack_size = maxStackSize;
833 public ExecutionContext ExecutionContext {
834 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
837 _ec = new ExecutionContext ();
845 internal bool HasExecutionContext {
851 internal void BranchExecutionContext (out ExecutionContext.Switcher switcher)
854 switcher = new ExecutionContext.Switcher ();
856 switcher = new ExecutionContext.Switcher (_ec);
857 _ec.CopyOnWrite = true;
861 internal void RestoreExecutionContext (ref ExecutionContext.Switcher switcher)
863 if (switcher.IsEmpty) {
868 switcher.Restore (_ec);
871 public int ManagedThreadId {
872 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
874 return Internal.managed_id;
878 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
879 public static void BeginCriticalRegion ()
881 CurrentThread.Internal.critical_region_level++;
884 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
885 public static void EndCriticalRegion ()
887 CurrentThread.Internal.critical_region_level--;
890 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
891 public static void BeginThreadAffinity ()
893 // Managed and native threads are currently bound together.
896 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
897 public static void EndThreadAffinity ()
899 // Managed and native threads are currently bound together.
902 public ApartmentState GetApartmentState ()
904 return (ApartmentState)Internal.apartment_state;
907 public void SetApartmentState (ApartmentState state)
909 if (!TrySetApartmentState (state))
910 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
913 public bool TrySetApartmentState (ApartmentState state)
915 if ((ThreadState & ThreadState.Unstarted) == 0)
916 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
918 if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown &&
919 (ApartmentState)Internal.apartment_state != state)
922 Internal.apartment_state = (byte)state;
928 public override int GetHashCode ()
930 return ManagedThreadId;
933 public void Start (object parameter)
935 m_ThreadStartArg = parameter;
940 void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
942 throw new NotImplementedException ();
945 void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
947 throw new NotImplementedException ();
950 void _Thread.GetTypeInfoCount (out uint pcTInfo)
952 throw new NotImplementedException ();
955 void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
956 IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
958 throw new NotImplementedException ();
962 internal CultureInfo GetCurrentUICultureNoAppX ()
964 return CultureInfo.CurrentUICulture;