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