2007-10-15 Dick Porter <dick@ximian.com>
[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;
40 using System.Security;
41
42 #if NET_2_0
43 using System.Runtime.ConstrainedExecution;
44 #endif
45
46 namespace System.Threading {
47
48         [ClassInterface (ClassInterfaceType.None)]
49 #if NET_2_0
50         [ComVisible (true)]
51         [ComDefaultInterface (typeof (_Thread))]
52         public sealed class Thread : CriticalFinalizerObject, _Thread {
53 #else
54         public sealed class Thread : _Thread {
55 #endif
56
57                 #region Sync with metadata/object-internals.h
58                 int lock_thread_id;
59                 // stores a thread handle
60                 private IntPtr system_thread_handle;
61
62                 /* Note this is an opaque object (an array), not a CultureInfo */
63                 private object cached_culture_info;
64                 private IntPtr unused0;
65                 private bool threadpool_thread;
66                 /* accessed only from unmanaged code */
67                 private IntPtr name;
68                 private int name_len; 
69                 private ThreadState state = ThreadState.Unstarted;
70                 private object abort_exc;
71                 internal object abort_state;
72                 /* thread_id is only accessed from unmanaged code */
73                 private Int64 thread_id;
74                 
75                 /* start_notify is used by the runtime to signal that Start()
76                  * is ok to return
77                  */
78                 private IntPtr start_notify;
79                 private IntPtr stack_ptr;
80                 private UIntPtr static_data; /* GC-tracked */
81                 private IntPtr jit_data;
82                 private IntPtr lock_data;
83                 Context current_appcontext;
84                 int stack_size;
85                 object start_obj;
86                 private IntPtr appdomain_refs;
87                 private bool interruption_requested;
88                 private IntPtr suspend_event;
89                 private IntPtr suspended_event;
90                 private IntPtr resume_event;
91                 /* Don't lock on synch_cs in managed code, since it can result in deadlocks */
92                 private object synch_cs = null;
93                 private IntPtr serialized_culture_info;
94                 private int serialized_culture_info_len;
95                 private IntPtr serialized_ui_culture_info;
96                 private int serialized_ui_culture_info_len;
97                 private ExecutionContext _ec;
98                 private bool thread_dump_requested;
99                 private IntPtr end_stack;
100                 private bool thread_interrupt_requested;
101                 private byte apartment_state = (byte)ApartmentState.Unknown;
102                 /* 
103                  * These fields are used to avoid having to increment corlib versions
104                  * when a new field is added to the unmanaged MonoThread structure.
105                  */
106                 private IntPtr unused5;
107                 private IntPtr unused6;
108                 private IntPtr unused7;
109                 #endregion
110
111                 // the name of local_slots is important as it's used by the runtime.
112                 [ThreadStatic] 
113                 static object[] local_slots;
114
115                 // can be both a ThreadSart and a ParameterizedThreadStart
116                 private MulticastDelegate threadstart;
117                 private string thread_name=null;
118                 
119                 private static int _managed_id_counter;
120                 private int managed_id;
121                 
122                 private IPrincipal _principal;
123
124                 public static Context CurrentContext {
125                         [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
126                         get {
127                                 return(AppDomain.InternalGetContext ());
128                         }
129                 }
130
131                 public static IPrincipal CurrentPrincipal {
132                         get {
133                                 IPrincipal p = null;
134                                 Thread th = CurrentThread;
135                                 lock (th) {
136                                         p = th._principal;
137                                         if (p == null) {
138                                                 p = GetDomain ().DefaultPrincipal;
139                                                 th._principal = p;
140                                         }
141                                 }
142                                 return p;
143                         }
144                         [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
145                         set {
146                                 CurrentThread._principal = value;
147                         }
148                 }
149
150                 // Looks up the object associated with the current thread
151                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
152                 private extern static Thread CurrentThread_internal();
153                 
154                 public static Thread CurrentThread {
155 #if NET_2_0
156                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
157 #endif
158                         get {
159                                 return(CurrentThread_internal());
160                         }
161                 }
162
163                 internal static int CurrentThreadId {
164                         get {
165                                 return (int)(CurrentThread.thread_id);
166                         }
167                 }
168
169                 // Stores a hash keyed by strings of LocalDataStoreSlot objects
170                 static Hashtable datastorehash;
171                 private static object datastore_lock = new object ();
172                 
173                 private static void InitDataStoreHash () {
174                         lock (datastore_lock) {
175                                 if (datastorehash == null) {
176                                         datastorehash = Hashtable.Synchronized(new Hashtable());
177                                 }
178                         }
179                 }
180                 
181                 public static LocalDataStoreSlot AllocateNamedDataSlot (string name) {
182                         lock (datastore_lock) {
183                                 if (datastorehash == null)
184                                         InitDataStoreHash ();
185                                 LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
186                                 if (slot != null) {
187                                         // This exception isnt documented (of
188                                         // course) but .net throws it
189                                         throw new ArgumentException("Named data slot already added");
190                                 }
191                         
192                                 slot = AllocateDataSlot ();
193
194                                 datastorehash.Add (name, slot);
195
196                                 return slot;
197                         }
198                 }
199
200                 public static void FreeNamedDataSlot (string name) {
201                         lock (datastore_lock) {
202                                 if (datastorehash == null)
203                                         InitDataStoreHash ();
204                                 LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
205
206                                 if (slot != null) {
207                                         datastorehash.Remove (slot);
208                                 }
209                         }
210                 }
211
212                 public static LocalDataStoreSlot AllocateDataSlot () {
213                         return new LocalDataStoreSlot (true);
214                 }
215
216                 public static object GetData (LocalDataStoreSlot slot) {
217                         object[] slots = local_slots;
218                         if (slot == null)
219                                 throw new ArgumentNullException ("slot");
220                         if (slots != null && slot.slot < slots.Length)
221                                 return slots [slot.slot];
222                         return null;
223                 }
224
225                 public static void SetData (LocalDataStoreSlot slot, object data) {
226                         object[] slots = local_slots;
227                         if (slot == null)
228                                 throw new ArgumentNullException ("slot");
229                         if (slots == null) {
230                                 slots = new object [slot.slot + 2];
231                                 local_slots = slots;
232                         } else if (slot.slot >= slots.Length) {
233                                 object[] nslots = new object [slot.slot + 2];
234                                 slots.CopyTo (nslots, 0);
235                                 slots = nslots;
236                                 local_slots = slots;
237                         }
238                         slots [slot.slot] = data;
239                 }
240
241                 public static AppDomain GetDomain() {
242                         return AppDomain.CurrentDomain;
243                 }
244
245                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
246                 public extern static int GetDomainID();
247
248                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
249                 internal extern static void FreeLocalSlotValues (int slot, bool thread_local);
250
251                 public static LocalDataStoreSlot GetNamedDataSlot(string name) {
252                         lock (datastore_lock) {
253                                 if (datastorehash == null)
254                                         InitDataStoreHash ();
255                                 LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
256
257                                 if(slot==null) {
258                                         slot=AllocateNamedDataSlot(name);
259                                 }
260                         
261                                 return(slot);
262                         }
263                 }
264                 
265                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
266                 private extern static void ResetAbort_internal();
267
268                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
269                 public static void ResetAbort ()
270                 {
271                         ResetAbort_internal ();
272                 }
273
274                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
275                 private extern static void Sleep_internal(int ms);
276
277                 public static void Sleep(int millisecondsTimeout) {
278                         if((millisecondsTimeout<0) && (millisecondsTimeout != Timeout.Infinite)) {
279                                 throw new ArgumentException("Negative timeout");
280                         }
281                         Sleep_internal(millisecondsTimeout);
282                 }
283
284                 public static void Sleep(TimeSpan timeout) {
285                         // LAMESPEC: says to throw ArgumentException too
286                         int ms=Convert.ToInt32(timeout.TotalMilliseconds);
287                         
288                         if(ms < 0 || ms > Int32.MaxValue) {
289                                 throw new ArgumentOutOfRangeException("Timeout out of range");
290                         }
291
292                         Sleep_internal(ms);
293                 }
294
295                 // Returns the system thread handle
296                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
297                 private extern IntPtr Thread_internal (MulticastDelegate start);
298
299                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
300                 private extern void Thread_init ();
301
302                 private static int GetNewManagedId() {
303                         return Interlocked.Increment(ref _managed_id_counter);
304                 }
305
306                 public Thread(ThreadStart start) {
307                         if(start==null) {
308                                 throw new ArgumentNullException("Null ThreadStart");
309                         }
310                         threadstart=start;
311
312                         Thread_init ();
313                         managed_id=GetNewManagedId();
314                 }
315
316 #if NET_2_0
317                 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
318 #endif
319                 public ApartmentState ApartmentState {
320                         get {
321                                 if ((ThreadState & ThreadState.Stopped) != 0)
322                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
323
324                                 return (ApartmentState)apartment_state;
325                         }
326
327                         set     {
328 #if NET_2_0
329                                 TrySetApartmentState (value);
330 #else
331                                 if ((ThreadState & ThreadState.Unstarted) == 0)
332                                         throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
333
334                                 if (value != ApartmentState.STA && value != ApartmentState.MTA)
335                                         throw new ArgumentException ("value is not a valid apartment state.");
336
337                                 if ((ApartmentState)apartment_state == ApartmentState.Unknown)
338                                         apartment_state = (byte)value;
339 #endif
340                         }
341                 }
342
343                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
344                 private static extern int current_lcid ();
345
346                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
347                 private extern CultureInfo GetCachedCurrentCulture ();
348
349                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
350                 private extern byte[] GetSerializedCurrentCulture ();
351
352                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
353                 private extern void SetCachedCurrentCulture (CultureInfo culture);
354
355                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
356                 private extern void SetSerializedCurrentCulture (byte[] culture);
357
358                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
359                 private extern CultureInfo GetCachedCurrentUICulture ();
360
361                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
362                 private extern byte[] GetSerializedCurrentUICulture ();
363
364                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
365                 private extern void SetCachedCurrentUICulture (CultureInfo culture);
366
367                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
368                 private extern void SetSerializedCurrentUICulture (byte[] culture);
369
370                 /* If the current_lcid() isn't known by CultureInfo,
371                  * it will throw an exception which may cause
372                  * String.Concat to try and recursively look up the
373                  * CurrentCulture, which will throw an exception, etc.
374                  * Use a boolean to short-circuit this scenario.
375                  */
376                 private static bool in_currentculture=false;
377
378                 static object culture_lock = new object ();
379                 
380                 /*
381                  * Thread objects are shared between appdomains, and CurrentCulture
382                  * should always return an object in the calling appdomain. See bug
383                  * http://bugzilla.ximian.com/show_bug.cgi?id=50049 for more info.
384                  * This is hard to implement correctly and efficiently, so the current
385                  * implementation is not perfect: changes made in one appdomain to the 
386                  * state of the current cultureinfo object are not visible to other 
387                  * appdomains.
388                  */             
389                 public CultureInfo CurrentCulture {
390                         get {
391                                 if (in_currentculture)
392                                         /* Bail out */
393                                         return CultureInfo.InvariantCulture;
394
395                                 CultureInfo culture = GetCachedCurrentCulture ();
396                                 if (culture != null)
397                                         return culture;
398
399                                 byte[] arr = GetSerializedCurrentCulture ();
400                                 if (arr == null) {
401                                         lock (culture_lock) {
402                                                 in_currentculture=true;
403                                                 culture = CultureInfo.ConstructCurrentCulture ();
404                                                 //
405                                                 // Don't serialize the culture in this case to avoid
406                                                 // initializing the serialization infrastructure in the
407                                                 // common case when the culture is not set explicitly.
408                                                 //
409                                                 SetCachedCurrentCulture (culture);
410                                                 in_currentculture = false;
411                                                 return culture;
412                                         }
413                                 }
414
415                                 /*
416                                  * No cultureinfo object exists for this domain, so create one
417                                  * by deserializing the serialized form.
418                                  */
419                                 in_currentculture = true;
420                                 try {
421                                         BinaryFormatter bf = new BinaryFormatter ();
422                                         MemoryStream ms = new MemoryStream (arr);
423                                         culture = (CultureInfo)bf.Deserialize (ms);
424                                         SetCachedCurrentCulture (culture);
425                                 } finally {
426                                         in_currentculture = false;
427                                 }
428
429                                 return culture;
430                         }
431                         
432                         [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
433                         set {
434                                 if (value == null)
435                                         throw new ArgumentNullException ("value");
436
437                                 value.CheckNeutral ();
438                                 in_currentculture = true;
439                                 try {
440                                         BinaryFormatter bf = new BinaryFormatter();
441                                         MemoryStream ms = new MemoryStream ();
442                                         bf.Serialize (ms, value);
443
444                                         SetCachedCurrentCulture (value);
445                                         SetSerializedCurrentCulture (ms.GetBuffer ());
446                                 } finally {
447                                         in_currentculture = false;
448                                 }
449                         }
450                 }
451
452                 public CultureInfo CurrentUICulture {
453                         get {
454                                 if (in_currentculture)
455                                         /* Bail out */
456                                         return CultureInfo.InvariantCulture;
457
458                                 CultureInfo culture = GetCachedCurrentUICulture ();
459                                 if (culture != null)
460                                         return culture;
461
462                                 byte[] arr = GetSerializedCurrentUICulture ();
463                                 if (arr == null) {
464                                         lock (culture_lock) {
465                                                 in_currentculture=true;
466                                                 /* We don't
467                                                  * distinguish
468                                                  * between
469                                                  * System and
470                                                  * UI cultures
471                                                  */
472                                                 culture = CultureInfo.ConstructCurrentUICulture ();
473                                                 //
474                                                 // Don't serialize the culture in this case to avoid
475                                                 // initializing the serialization infrastructure in the
476                                                 // common case when the culture is not set explicitly.
477                                                 //
478                                                 SetCachedCurrentUICulture (culture);
479                                                 in_currentculture = false;
480                                                 return culture;
481                                         }
482                                 }
483
484                                 /*
485                                  * No cultureinfo object exists for this domain, so create one
486                                  * by deserializing the serialized form.
487                                  */
488                                 in_currentculture = true;
489                                 try {
490                                         BinaryFormatter bf = new BinaryFormatter ();
491                                         MemoryStream ms = new MemoryStream (arr);
492                                         culture = (CultureInfo)bf.Deserialize (ms);
493                                         SetCachedCurrentUICulture (culture);
494                                 }
495                                 finally {
496                                         in_currentculture = false;
497                                 }
498
499                                 return culture;
500                         }
501                         
502                         set {
503                                 in_currentculture = true;
504                                 
505                                 if (value == null)
506                                         throw new ArgumentNullException ("value");
507
508                                 try {
509                                         BinaryFormatter bf = new BinaryFormatter();
510                                         MemoryStream ms = new MemoryStream ();
511                                         bf.Serialize (ms, value);
512
513                                         SetCachedCurrentUICulture (value);
514                                         SetSerializedCurrentUICulture (ms.GetBuffer ());
515                                 } finally {
516                                         in_currentculture = false;
517                                 }
518                         }
519                 }
520
521                 public bool IsThreadPoolThread {
522                         get {
523                                 return IsThreadPoolThreadInternal;
524                         }
525                 }
526
527                 internal bool IsThreadPoolThreadInternal {
528                         get {
529                                 return threadpool_thread;
530                         }
531                         set {
532                                 threadpool_thread = value;
533                         }
534                 }
535
536                 public bool IsAlive {
537                         get {
538                                 ThreadState curstate = GetState ();
539                                 
540                                 if((curstate & ThreadState.Aborted) != 0 ||
541                                    (curstate & ThreadState.Stopped) != 0 ||
542                                    (curstate & ThreadState.Unstarted) != 0) {
543                                         return(false);
544                                 } else {
545                                         return(true);
546                                 }
547                         }
548                 }
549
550                 public bool IsBackground {
551                         get {
552                                 ThreadState thread_state = GetState ();
553                                 if ((thread_state & ThreadState.Stopped) != 0)
554                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
555
556                                 return (thread_state & ThreadState.Background) != 0;
557                         }
558                         
559                         set {
560                                 if (value) {
561                                         SetState (ThreadState.Background);
562                                 } else {
563                                         ClrState (ThreadState.Background);
564                                 }
565                         }
566                 }
567
568                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
569                 private extern string GetName_internal ();
570
571                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
572                 private extern void SetName_internal (String name);
573
574                 /* 
575                  * The thread name must be shared by appdomains, so it is stored in
576                  * unmanaged code.
577                  */
578
579                 public string Name {
580                         get {
581                                 return GetName_internal ();
582                         }
583                         
584                         set {
585                                 SetName_internal (value);
586                         }
587                 }
588
589                 public ThreadPriority Priority {
590                         get {
591                                 return(ThreadPriority.Lowest);
592                         }
593                         
594                         set {
595                                 // FIXME: Implement setter.
596                         }
597                 }
598
599                 public ThreadState ThreadState {
600                         get {
601                                 return GetState ();
602                         }
603                 }
604
605                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
606                 private extern void Abort_internal (object stateInfo);
607
608                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
609                 public void Abort () 
610                 {
611                         Abort_internal (null);
612                 }
613
614                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
615                 public void Abort (object stateInfo) 
616                 {
617                         Abort_internal (stateInfo);
618                 }
619                 
620                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
621                 private extern void Interrupt_internal ();
622                 
623                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
624                 public void Interrupt ()
625                 {
626                         Interrupt_internal ();
627                 }
628
629                 // The current thread joins with 'this'. Set ms to 0 to block
630                 // until this actually exits.
631                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
632                 private extern bool Join_internal(int ms, IntPtr handle);
633                 
634                 public void Join()
635                 {
636                         Join_internal(Timeout.Infinite, system_thread_handle);
637                 }
638
639                 public bool Join(int millisecondsTimeout)
640                 {
641                         if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout < 0)
642                                 throw new ArgumentException ("Timeout less than zero", "millisecondsTimeout");
643
644                         return Join_internal(millisecondsTimeout, system_thread_handle);
645                 }
646
647                 public bool Join(TimeSpan timeout)
648                 {
649                         // LAMESPEC: says to throw ArgumentException too
650                         int ms=Convert.ToInt32(timeout.TotalMilliseconds);
651                         
652                         if(ms < 0 || ms > Int32.MaxValue) {
653                                 throw new ArgumentOutOfRangeException("timeout out of range");
654                         }
655                         return Join_internal(ms, system_thread_handle);
656                 }
657
658 #if NET_1_1
659                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
660                 public extern static void MemoryBarrier ();
661 #endif
662                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
663                 private extern void Resume_internal();
664
665 #if NET_2_0
666                 [Obsolete ("")]
667 #endif
668                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
669                 public void Resume () 
670                 {
671                         Resume_internal ();
672                 }
673
674                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
675                 private extern static void SpinWait_internal (int iterations);
676
677
678 #if NET_2_0
679                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
680 #endif
681                 public static void SpinWait (int iterations) 
682                 {
683                         SpinWait_internal (iterations);
684                 }
685
686                 public void Start() {
687                         // propagate informations from the original thread to the new thread
688 #if NET_2_0
689                         if (!ExecutionContext.IsFlowSuppressed ())
690                                 _ec = ExecutionContext.Capture ();
691 #else
692                         // before 2.0 this was only used for security (mostly CAS) so we
693                         // do this only if the security manager is active
694                         if (SecurityManager.SecurityEnabled)
695                                 _ec = ExecutionContext.Capture ();
696 #endif
697                         if (CurrentThread._principal != null)
698                                 _principal = CurrentThread._principal;
699
700                         // Thread_internal creates and starts the new thread, 
701                         if (Thread_internal(threadstart) == (IntPtr) 0)
702                                 throw new SystemException ("Thread creation failed.");
703                 }
704
705                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
706                 private extern void Suspend_internal();
707
708 #if NET_2_0
709                 [Obsolete ("")]
710 #endif
711                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
712                 public void Suspend ()
713                 {
714                         Suspend_internal ();
715                 }
716
717                 // Closes the system thread handle
718                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
719                 private extern void Thread_free_internal(IntPtr handle);
720
721 #if NET_2_0
722                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
723 #endif
724                 ~Thread() {
725                         // Free up the handle
726                         if (system_thread_handle != (IntPtr) 0)
727                                 Thread_free_internal(system_thread_handle);
728                 }
729
730                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
731                 extern private void SetState (ThreadState set);
732                 
733                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
734                 extern private void ClrState (ThreadState clr);
735                 
736                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
737                 extern private ThreadState GetState ();
738
739 #if NET_1_1
740                 
741                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
742                 extern public static byte VolatileRead (ref byte address);
743                 
744                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
745                 extern public static double VolatileRead (ref double address);
746                 
747                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
748                 extern public static short VolatileRead (ref short address);
749                 
750                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
751                 extern public static int VolatileRead (ref int address);
752                 
753                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
754                 extern public static long VolatileRead (ref long address);
755                 
756                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
757                 extern public static IntPtr VolatileRead (ref IntPtr address);
758                 
759                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
760                 extern public static object VolatileRead (ref object address);
761
762                 [CLSCompliant(false)]
763                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
764                 extern public static sbyte VolatileRead (ref sbyte address);
765                 
766                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
767                 extern public static float VolatileRead (ref float address);
768
769                 [CLSCompliant (false)]
770                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
771                 extern public static ushort VolatileRead (ref ushort address);
772
773                 [CLSCompliant (false)]
774                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
775                 extern public static uint VolatileRead (ref uint address);
776
777                 [CLSCompliant (false)]
778                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
779                 extern public static ulong VolatileRead (ref ulong address);
780
781                 [CLSCompliant (false)]
782                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
783                 extern public static UIntPtr VolatileRead (ref UIntPtr address);
784
785                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
786                 extern public static void VolatileWrite (ref byte address, byte value);
787                 
788                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
789                 extern public static void VolatileWrite (ref double address, double value);
790                 
791                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
792                 extern public static void VolatileWrite (ref short address, short value);
793                 
794                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
795                 extern public static void VolatileWrite (ref int address, int value);
796                 
797                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
798                 extern public static void VolatileWrite (ref long address, long value);
799                 
800                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
801                 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
802                 
803                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
804                 extern public static void VolatileWrite (ref object address, object value);
805
806                 [CLSCompliant(false)]
807                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
808                 extern public static void VolatileWrite (ref sbyte address, sbyte value);
809                 
810                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
811                 extern public static void VolatileWrite (ref float address, float value);
812
813                 [CLSCompliant (false)]
814                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
815                 extern public static void VolatileWrite (ref ushort address, ushort value);
816
817                 [CLSCompliant (false)]
818                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
819                 extern public static void VolatileWrite (ref uint address, uint value);
820
821                 [CLSCompliant (false)]
822                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
823                 extern public static void VolatileWrite (ref ulong address, ulong value);
824
825                 [CLSCompliant (false)]
826                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
827                 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
828                 
829 #endif
830
831 #if NET_2_0
832                 public Thread (ThreadStart start, int maxStackSize)
833                 {
834                         if (start == null)
835                                 throw new ArgumentNullException ("start");
836                         if (maxStackSize < 131072)
837                                 throw new ArgumentException ("< 128 kb", "maxStackSize");
838
839                         threadstart = start;
840                         stack_size = maxStackSize;
841                         managed_id = GetNewManagedId();
842                 }
843
844                 public Thread (ParameterizedThreadStart start)
845                 {
846                         if (start == null)
847                                 throw new ArgumentNullException ("start");
848
849                         threadstart = start;
850                         managed_id = GetNewManagedId();
851                 }
852
853                 public Thread (ParameterizedThreadStart start, int maxStackSize)
854                 {
855                         if (start == null)
856                                 throw new ArgumentNullException ("start");
857                         if (maxStackSize < 131072)
858                                 throw new ArgumentException ("< 128 kb", "maxStackSize");
859
860                         threadstart = start;
861                         stack_size = maxStackSize;
862                         managed_id = GetNewManagedId();
863                 }
864
865                 [MonoTODO ("limited to CompressedStack support")]
866                 // FIXME: We share the _ec object between appdomains
867                 public ExecutionContext ExecutionContext {
868                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
869                         get {
870                                 if (_ec == null)
871                                         _ec = new ExecutionContext ();
872                                 return _ec;
873                         }
874                 }
875
876                 public int ManagedThreadId {
877                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
878                         get { return managed_id; }
879                 }
880
881                 [MonoTODO("Not implemented")]
882                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
883                 public static void BeginCriticalRegion ()
884                 {
885                         throw new NotImplementedException ();
886                 }
887
888                 [MonoTODO("Not implemented")]
889                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
890                 public static void EndCriticalRegion ()
891                 {
892                         throw new NotImplementedException ();
893                 }
894
895                 [MonoTODO("Not implemented")]
896                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
897                 public static void BeginThreadAffinity ()
898                 {
899                         throw new NotImplementedException ();
900                 }
901
902                 [MonoTODO("Not implemented")]
903                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
904                 public static void EndThreadAffinity ()
905                 {
906                         throw new NotImplementedException ();
907                 }
908                 
909                 public ApartmentState GetApartmentState ()
910                 {
911                         return (ApartmentState)apartment_state;
912                 }
913
914                 public void SetApartmentState (ApartmentState state)
915                 {
916                         if (!TrySetApartmentState (state))
917                                 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
918                 }
919
920                 public bool TrySetApartmentState (ApartmentState state) 
921                 {
922                         if ((ThreadState & ThreadState.Unstarted) == 0)
923                                 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
924
925                         if ((ApartmentState)apartment_state != ApartmentState.Unknown)
926                                 return false;
927
928                         apartment_state = (byte)state;
929
930                         return true;
931                 }
932                 
933                 [ComVisible (false)]
934                 public override int GetHashCode ()
935                 {
936                         return managed_id;
937                 }
938
939                 public void Start (object parameter)
940                 {
941                         start_obj = parameter;
942                         Start ();
943                 }
944 #else
945                 internal ExecutionContext ExecutionContext {
946                         get {
947                                 if (_ec == null)
948                                         _ec = new ExecutionContext ();
949                                 return _ec;
950                         }
951                 }
952 #endif
953
954                 // NOTE: This method doesn't show in the class library status page because
955                 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
956                 // But it's there!
957                 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
958                 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
959 #if NET_2_0
960                 [Obsolete ("see CompressedStack class")]
961 #endif
962 #if NET_1_1
963                 public
964 #else
965                 internal
966 #endif
967                 CompressedStack GetCompressedStack ()
968                 {
969                         // Note: returns null if no CompressedStack has been set.
970                         // However CompressedStack.GetCompressedStack returns an 
971                         // (empty?) CompressedStack instance.
972                         CompressedStack cs = ExecutionContext.SecurityContext.CompressedStack;
973                         return ((cs == null) || cs.IsEmpty ()) ? null : cs.CreateCopy ();
974                 }
975
976                 // NOTE: This method doesn't show in the class library status page because
977                 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
978                 // But it's there!
979                 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
980                 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
981 #if NET_2_0
982                 [Obsolete ("see CompressedStack class")]
983 #endif
984 #if NET_1_1
985                 public
986 #else
987                 internal
988 #endif
989                 void SetCompressedStack (CompressedStack stack)
990                 {
991                         ExecutionContext.SecurityContext.CompressedStack = stack;
992                 }
993
994 #if NET_1_1
995                 void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
996                 {
997                         throw new NotImplementedException ();
998                 }
999
1000                 void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1001                 {
1002                         throw new NotImplementedException ();
1003                 }
1004
1005                 void _Thread.GetTypeInfoCount (out uint pcTInfo)
1006                 {
1007                         throw new NotImplementedException ();
1008                 }
1009
1010                 void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1011                         IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1012                 {
1013                         throw new NotImplementedException ();
1014                 }
1015 #endif
1016         }
1017 }