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