Merge pull request #2408 from tastywheattasteslikechicken/MoreInterfaceSupport
[mono.git] / mcs / class / corlib / System.Threading / Thread.cs
1 //
2 // System.Threading.Thread.cs
3 //
4 // Author:
5 //   Dick Porter (dick@ximian.com)
6 //
7 // (C) Ximian, Inc.  http://www.ximian.com
8 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
9 //
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:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
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.
28 //
29
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;
38 using System.IO;
39 using System.Collections.Generic;
40 using System.Reflection;
41 using System.Security;
42 using System.Diagnostics;
43 using System.Runtime.ConstrainedExecution;
44
45 namespace System.Threading {
46         [StructLayout (LayoutKind.Sequential)]
47         sealed class InternalThread : CriticalFinalizerObject {
48 #pragma warning disable 169, 414, 649
49                 #region Sync with metadata/object-internals.h
50                 int lock_thread_id;
51                 // stores a thread handle
52                 IntPtr handle;
53                 IntPtr native_handle; // used only on Win32
54
55                 /* Note this is an opaque object (an array), not a CultureInfo */
56                 private object cached_culture_info;
57                 /* accessed only from unmanaged code */
58                 private IntPtr name;
59                 private int name_len; 
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;
65                 
66                 /* start_notify is used by the runtime to signal that Start()
67                  * is ok to return
68                  */
69                 private IntPtr stack_ptr;
70                 private UIntPtr static_data; /* GC-tracked */
71                 private IntPtr runtime_thread_info;
72                 /* current System.Runtime.Remoting.Contexts.Context instance
73                    keep as an object to avoid triggering its class constructor when not needed */
74                 private object current_appcontext;
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;
88                 private int small_id;
89                 private IntPtr manage_callback;
90                 private IntPtr interrupt_on_stop;
91                 private IntPtr flags;
92                 private IntPtr thread_pinning_ref;
93                 private IntPtr abort_protected_block_count;
94                 private int priority = (int) ThreadPriority.Normal;
95                 private IntPtr owned_mutex;
96                 private IntPtr suspended_event;
97                 /* 
98                  * These fields are used to avoid having to increment corlib versions
99                  * when a new field is added to the unmanaged MonoThread structure.
100                  */
101                 private IntPtr unused1;
102                 private IntPtr unused2;
103
104                 /* This is used only to check that we are in sync between the representation
105                  * of MonoInternalThread in native and InternalThread in managed
106                  *
107                  * DO NOT RENAME! DO NOT ADD FIELDS AFTER! */
108                 private IntPtr last;
109                 #endregion
110 #pragma warning restore 169, 414, 649
111
112                 // Closes the system thread handle
113                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
114                 private extern void Thread_free_internal();
115
116                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
117                 ~InternalThread() {
118                         Thread_free_internal();
119                 }
120         }
121
122         [StructLayout (LayoutKind.Sequential)]
123         public sealed partial class Thread {
124 #pragma warning disable 414             
125                 #region Sync with metadata/object-internals.h
126                 private InternalThread internal_thread;
127                 object m_ThreadStartArg;
128                 object pending_exception;
129                 #endregion
130 #pragma warning restore 414
131
132                 IPrincipal principal;
133                 int principal_version;
134
135                 // the name of current_thread is
136                 // important because they are used by the runtime.
137
138                 [ThreadStatic]
139                 static Thread current_thread;
140
141                 // can be both a ThreadStart and a ParameterizedThreadStart
142                 private MulticastDelegate m_Delegate;
143
144                 private ExecutionContext m_ExecutionContext;    // this call context follows the logical thread
145
146                 private bool m_ExecutionContextBelongsToOuterScope;
147
148                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
149                 private extern void ConstructInternalThread ();
150
151                 private InternalThread Internal {
152                         get {
153                                 if (internal_thread == null)
154                                         ConstructInternalThread ();
155                                 return internal_thread;
156                         }
157                 }
158
159                 public static Context CurrentContext {
160                         [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
161                         get {
162                                 return(AppDomain.InternalGetContext ());
163                         }
164                 }
165
166                 /*
167                  * These two methods return an array in the target
168                  * domain with the same content as the argument.  If
169                  * the argument is already in the target domain, then
170                  * the argument is returned, otherwise a copy.
171                  */
172                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
173                 private extern static byte[] ByteArrayToRootDomain (byte[] arr);
174
175                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
176                 private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
177
178                 static void DeserializePrincipal (Thread th)
179                 {
180                         MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
181                         int type = ms.ReadByte ();
182                         if (type == 0) {
183                                 BinaryFormatter bf = new BinaryFormatter ();
184                                 th.principal = (IPrincipal) bf.Deserialize (ms);
185                                 th.principal_version = th.Internal._serialized_principal_version;
186                         } else if (type == 1) {
187                                 BinaryReader reader = new BinaryReader (ms);
188                                 string name = reader.ReadString ();
189                                 string auth_type = reader.ReadString ();
190                                 int n_roles = reader.ReadInt32 ();
191                                 string [] roles = null;
192                                 if (n_roles >= 0) {
193                                         roles = new string [n_roles];
194                                         for (int i = 0; i < n_roles; i++)
195                                                 roles [i] = reader.ReadString ();
196                                 }
197                                 th.principal = new GenericPrincipal (new GenericIdentity (name, auth_type), roles);
198                         } else if (type == 2 || type == 3) {
199                                 string [] roles = type == 2 ? null : new string [0];
200                                 th.principal = new GenericPrincipal (new GenericIdentity ("", ""), roles);
201                         }
202                 }
203
204                 static void SerializePrincipal (Thread th, IPrincipal value)
205                 {
206                         MemoryStream ms = new MemoryStream ();
207                         bool done = false;
208                         if (value.GetType () == typeof (GenericPrincipal)) {
209                                 GenericPrincipal gp = (GenericPrincipal) value;
210                                 if (gp.Identity != null && gp.Identity.GetType () == typeof (GenericIdentity)) {
211                                         GenericIdentity id = (GenericIdentity) gp.Identity;
212                                         if (id.Name == "" && id.AuthenticationType == "") {
213                                                 if (gp.Roles == null) {
214                                                         ms.WriteByte (2);
215                                                         done = true;
216                                                 } else if (gp.Roles.Length == 0) {
217                                                         ms.WriteByte (3);
218                                                         done = true;
219                                                 }
220                                         } else {
221                                                 ms.WriteByte (1);
222                                                 BinaryWriter br = new BinaryWriter (ms);
223                                                 br.Write (gp.Identity.Name);
224                                                 br.Write (gp.Identity.AuthenticationType);
225                                                 string [] roles = gp.Roles;
226                                                 if  (roles == null) {
227                                                         br.Write ((int) (-1));
228                                                 } else {
229                                                         br.Write (roles.Length);
230                                                         foreach (string s in roles) {
231                                                                 br.Write (s);
232                                                         }
233                                                 }
234                                                 br.Flush ();
235                                                 done = true;
236                                         }
237                                 }
238                         }
239                         if (!done) {
240                                 ms.WriteByte (0);
241                                 BinaryFormatter bf = new BinaryFormatter ();
242                                 try {
243                                         bf.Serialize (ms, value);
244                                 } catch {}
245                         }
246                         th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
247                 }
248
249                 public static IPrincipal CurrentPrincipal {
250                         get {
251                                 Thread th = CurrentThread;
252
253                                 if (th.principal_version != th.Internal._serialized_principal_version)
254                                         th.principal = null;
255
256                                 if (th.principal != null)
257                                         return th.principal;
258
259                                 if (th.Internal._serialized_principal != null) {
260                                         try {
261                                                 DeserializePrincipal (th);
262                                                 return th.principal;
263                                         } catch {}
264                                 }
265
266                                 th.principal = GetDomain ().DefaultPrincipal;
267                                 th.principal_version = th.Internal._serialized_principal_version;
268                                 return th.principal;
269                         }
270                         [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
271                         set {
272                                 Thread th = CurrentThread;
273
274                                 if (value != GetDomain ().DefaultPrincipal) {
275                                         ++th.Internal._serialized_principal_version;
276                                         try {
277                                                 SerializePrincipal (th, value);
278                                         } catch (Exception) {
279                                                 th.Internal._serialized_principal = null;
280                                         }
281                                         th.principal_version = th.Internal._serialized_principal_version;
282                                 } else {
283                                         th.Internal._serialized_principal = null;
284                                 }
285
286                                 th.principal = value;
287                         }
288                 }
289
290                 // Looks up the object associated with the current thread
291                 // this is called by the JIT directly, too
292                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
293                 private extern static InternalThread CurrentInternalThread_internal();
294
295                 public static Thread CurrentThread {
296                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
297                         get {
298                                 if (current_thread == null)
299                                         current_thread = new Thread (CurrentInternalThread_internal ());
300                                 return current_thread;
301                         }
302                 }
303
304                 internal static int CurrentThreadId {
305                         get {
306                                 return (int)(CurrentThread.internal_thread.thread_id);
307                         }
308                 }
309
310                 public static AppDomain GetDomain() {
311                         return AppDomain.CurrentDomain;
312                 }
313
314                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
315                 public extern static int GetDomainID();
316
317                 // Returns the system thread handle
318                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
319                 private extern IntPtr Thread_internal (MulticastDelegate start);
320
321                 private Thread (InternalThread it) {
322                         internal_thread = it;
323                 }
324                 
325                 // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
326                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
327                 ~Thread ()
328                 {
329                 }
330
331                 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
332                 public ApartmentState ApartmentState {
333                         get {
334                                 if ((ThreadState & ThreadState.Stopped) != 0)
335                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
336
337                                 return (ApartmentState)Internal.apartment_state;
338                         }
339
340                         set {
341                                 TrySetApartmentState (value);
342                         }
343                 }
344
345                 public bool IsThreadPoolThread {
346                         get {
347                                 return IsThreadPoolThreadInternal;
348                         }
349                 }
350
351                 internal bool IsThreadPoolThreadInternal {
352                         get {
353                                 return Internal.threadpool_thread;
354                         }
355                         set {
356                                 Internal.threadpool_thread = value;
357                         }
358                 }
359
360                 public bool IsAlive {
361                         get {
362                                 ThreadState curstate = GetState (Internal);
363                                 
364                                 if((curstate & ThreadState.Aborted) != 0 ||
365                                    (curstate & ThreadState.Stopped) != 0 ||
366                                    (curstate & ThreadState.Unstarted) != 0) {
367                                         return(false);
368                                 } else {
369                                         return(true);
370                                 }
371                         }
372                 }
373
374                 public bool IsBackground {
375                         get {
376                                 ThreadState thread_state = GetState (Internal);
377                                 if ((thread_state & ThreadState.Stopped) != 0)
378                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
379
380                                 return (thread_state & ThreadState.Background) != 0;
381                         }
382                         
383                         set {
384                                 if (value) {
385                                         SetState (Internal, ThreadState.Background);
386                                 } else {
387                                         ClrState (Internal, ThreadState.Background);
388                                 }
389                         }
390                 }
391
392                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
393                 private extern static string GetName_internal (InternalThread thread);
394
395                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
396                 private extern static void SetName_internal (InternalThread thread, String name);
397
398                 /* 
399                  * The thread name must be shared by appdomains, so it is stored in
400                  * unmanaged code.
401                  */
402
403                 public string Name {
404                         get {
405                                 return GetName_internal (Internal);
406                         }
407                         
408                         set {
409                                 SetName_internal (Internal, value);
410                         }
411                 }
412
413                 public ThreadState ThreadState {
414                         get {
415                                 return GetState (Internal);
416                         }
417                 }
418
419 #if MONO_FEATURE_THREAD_ABORT
420                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
421                 private extern static void Abort_internal (InternalThread thread, object stateInfo);
422
423                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
424                 public void Abort () 
425                 {
426                         Abort_internal (Internal, null);
427                 }
428
429                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
430                 public void Abort (object stateInfo) 
431                 {
432                         Abort_internal (Internal, stateInfo);
433                 }
434
435                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
436                 extern object GetAbortExceptionState ();
437
438                 internal object AbortReason {
439                         get {
440                                 return GetAbortExceptionState ();
441                         }
442                 }
443
444                 void ClearAbortReason ()
445                 {
446                 }
447 #else
448                 [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
449                 public void Abort ()
450                 {
451                         throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
452                 }
453
454                 [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
455                 public void Abort (object stateInfo)
456                 {
457                         throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
458                 }
459
460                 [Obsolete ("Thread.ResetAbort is not supported on the current platform.", true)]
461                 public static void ResetAbort ()
462                 {
463                         throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
464                 }
465
466                 internal object AbortReason {
467                         get {
468                                 throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
469                         }
470                 }
471 #endif // MONO_FEATURE_THREAD_ABORT
472
473                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
474                 private extern static void SpinWait_nop ();
475
476
477                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
478                 public static void SpinWait (int iterations) 
479                 {
480                         if (iterations < 0)
481                                 return;
482                         while (iterations-- > 0)
483                         {
484                                 SpinWait_nop ();
485                         }
486                 }
487
488                 void StartInternal (IPrincipal principal, ref StackCrawlMark stackMark)
489                 {
490 #if FEATURE_ROLE_BASED_SECURITY
491                         Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
492 #endif
493
494                         // Thread_internal creates and starts the new thread, 
495                         if (Thread_internal(m_Delegate) == IntPtr.Zero)
496                                 throw new SystemException ("Thread creation failed.");
497
498                         m_ThreadStartArg = null;
499                 }
500
501                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
502                 extern private static void SetState (InternalThread thread, ThreadState set);
503
504                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
505                 extern private static void ClrState (InternalThread thread, ThreadState clr);
506
507                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
508                 extern private static ThreadState GetState (InternalThread thread);
509
510                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
511                 extern public static byte VolatileRead (ref byte address);
512                 
513                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
514                 extern public static double VolatileRead (ref double address);
515                 
516                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
517                 extern public static short VolatileRead (ref short address);
518                 
519                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
520                 extern public static int VolatileRead (ref int address);
521                 
522                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
523                 extern public static long VolatileRead (ref long address);
524                 
525                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
526                 extern public static IntPtr VolatileRead (ref IntPtr address);
527                 
528                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
529                 extern public static object VolatileRead (ref object address);
530
531                 [CLSCompliant(false)]
532                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
533                 extern public static sbyte VolatileRead (ref sbyte address);
534                 
535                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
536                 extern public static float VolatileRead (ref float address);
537
538                 [CLSCompliant (false)]
539                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
540                 extern public static ushort VolatileRead (ref ushort address);
541
542                 [CLSCompliant (false)]
543                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
544                 extern public static uint VolatileRead (ref uint address);
545
546                 [CLSCompliant (false)]
547                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
548                 extern public static ulong VolatileRead (ref ulong address);
549
550                 [CLSCompliant (false)]
551                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
552                 extern public static UIntPtr VolatileRead (ref UIntPtr address);
553
554                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
555                 extern public static void VolatileWrite (ref byte address, byte value);
556                 
557                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
558                 extern public static void VolatileWrite (ref double address, double value);
559                 
560                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
561                 extern public static void VolatileWrite (ref short address, short value);
562                 
563                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
564                 extern public static void VolatileWrite (ref int address, int value);
565                 
566                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
567                 extern public static void VolatileWrite (ref long address, long value);
568                 
569                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
570                 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
571                 
572                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
573                 extern public static void VolatileWrite (ref object address, object value);
574
575                 [CLSCompliant(false)]
576                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
577                 extern public static void VolatileWrite (ref sbyte address, sbyte value);
578                 
579                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
580                 extern public static void VolatileWrite (ref float address, float value);
581
582                 [CLSCompliant (false)]
583                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
584                 extern public static void VolatileWrite (ref ushort address, ushort value);
585
586                 [CLSCompliant (false)]
587                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
588                 extern public static void VolatileWrite (ref uint address, uint value);
589
590                 [CLSCompliant (false)]
591                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
592                 extern public static void VolatileWrite (ref ulong address, ulong value);
593
594                 [CLSCompliant (false)]
595                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
596                 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
597                 
598                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
599                 extern static int SystemMaxStackStize ();
600
601                 static int GetProcessDefaultStackSize (int maxStackSize)
602                 {
603                         if (maxStackSize == 0)
604                                 return 0;
605
606                         if (maxStackSize < 131072) // make sure stack is at least 128k big
607                                 return 131072;
608
609                         int page_size = Environment.GetPageSize ();
610
611                         if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
612                                 maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
613
614                         /* Respect the max stack size imposed by the system*/
615                         return Math.Min (maxStackSize, SystemMaxStackStize ());
616                 }
617
618                 void SetStart (MulticastDelegate start, int maxStackSize)
619                 {
620                         m_Delegate = start;
621                         Internal.stack_size = maxStackSize;
622                 }
623
624                 public int ManagedThreadId {
625                         [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
626                         get {
627                                 return Internal.managed_id;
628                         }
629                 }
630
631                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
632                 public static void BeginCriticalRegion ()
633                 {
634                         CurrentThread.Internal.critical_region_level++;
635                 }
636
637                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
638                 public static void EndCriticalRegion ()
639                 {
640                         CurrentThread.Internal.critical_region_level--;
641                 }
642
643                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
644                 public static void BeginThreadAffinity ()
645                 {
646                         // Managed and native threads are currently bound together.
647                 }
648
649                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
650                 public static void EndThreadAffinity ()
651                 {
652                         // Managed and native threads are currently bound together.
653                 }
654
655                 public ApartmentState GetApartmentState ()
656                 {
657                         return (ApartmentState)Internal.apartment_state;
658                 }
659
660                 public void SetApartmentState (ApartmentState state)
661                 {
662                         if (!TrySetApartmentState (state))
663                                 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
664                 }
665
666                 public bool TrySetApartmentState (ApartmentState state) 
667                 {
668                         if ((ThreadState & ThreadState.Unstarted) == 0)
669                                 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
670
671                         if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown && 
672                             (ApartmentState)Internal.apartment_state != state)
673                                 return false;
674
675                         Internal.apartment_state = (byte)state;
676
677                         return true;
678                 }
679                 
680                 [ComVisible (false)]
681                 public override int GetHashCode ()
682                 {
683                         return ManagedThreadId;
684                 }
685
686                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
687                 internal static extern void GetStackTraces (out Thread[] threads, out object[] stack_frames);
688
689                 // This is a mono extension to gather the stack traces for all running threads
690                 internal static Dictionary<Thread, StackTrace> Mono_GetStackTraces () {
691                         Thread[] threads;
692                         object[] stack_frames;
693
694                         GetStackTraces (out threads, out stack_frames);
695
696                         var res = new Dictionary<Thread, StackTrace> ();
697                         for (int i = 0; i < threads.Length; ++i)
698                                 res [threads [i]] = new StackTrace ((StackFrame[])stack_frames [i]);
699                         return res;
700                 }
701
702 #if !MONO_FEATURE_THREAD_SUSPEND_RESUME
703                 [Obsolete ("Thread.Suspend is not supported on the current platform.", true)]
704                 public void Suspend ()
705                 {
706                         throw new PlatformNotSupportedException ("Thread.Suspend is not supported on the current platform.");
707                 }
708
709                 [Obsolete ("Thread.Resume is not supported on the current platform.", true)]
710                 public void Resume ()
711                 {
712                         throw new PlatformNotSupportedException ("Thread.Resume is not supported on the current platform.");
713                 }
714 #endif
715
716                 public void DisableComObjectEagerCleanup ()
717                 {
718                         throw new PlatformNotSupportedException ();
719                 }
720         }
721 }