65aafccd49888ee3c1d3c262f4f695ddc4d55d9a
[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.Runtime.ConstrainedExecution;
43
44 namespace System.Threading {
45         [StructLayout (LayoutKind.Sequential)]
46         sealed class InternalThread : CriticalFinalizerObject {
47 #pragma warning disable 169, 414, 649
48                 #region Sync with metadata/object-internals.h
49                 int lock_thread_id;
50                 // stores a thread handle
51                 internal IntPtr system_thread_handle;
52
53                 /* Note this is an opaque object (an array), not a CultureInfo */
54                 private object cached_culture_info;
55                 /* accessed only from unmanaged code */
56                 private IntPtr name;
57                 private int name_len; 
58                 private ThreadState state;
59                 private object abort_exc;
60                 private int abort_state_handle;
61                 /* thread_id is only accessed from unmanaged code */
62                 internal Int64 thread_id;
63                 
64                 /* start_notify is used by the runtime to signal that Start()
65                  * is ok to return
66                  */
67                 private IntPtr start_notify;
68                 private IntPtr stack_ptr;
69                 private UIntPtr static_data; /* GC-tracked */
70                 private IntPtr runtime_thread_info;
71                 /* current System.Runtime.Remoting.Contexts.Context instance
72                    keep as an object to avoid triggering its class constructor when not needed */
73                 private object current_appcontext;
74                 private object pending_exception;
75                 private object root_domain_thread;
76                 internal byte[] _serialized_principal;
77                 internal int _serialized_principal_version;
78                 private IntPtr appdomain_refs;
79                 private int interruption_requested;
80                 private IntPtr synch_cs;
81                 internal bool threadpool_thread;
82                 private bool thread_interrupt_requested;
83                 /* These are used from managed code */
84                 internal int stack_size;
85                 internal byte apartment_state;
86                 internal volatile int critical_region_level;
87                 internal int managed_id;
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 async_invoke_method;
94                 /* 
95                  * These fields are used to avoid having to increment corlib versions
96                  * when a new field is added to the unmanaged MonoThread structure.
97                  */
98                 private IntPtr unused1;
99                 private IntPtr unused2;
100                 #endregion
101 #pragma warning restore 169, 414, 649
102
103                 // Closes the system thread handle
104                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
105                 private extern void Thread_free_internal(IntPtr handle);
106
107                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
108                 ~InternalThread() {
109                         Thread_free_internal(system_thread_handle);
110                 }
111         }
112
113         [StructLayout (LayoutKind.Sequential)]
114         public sealed partial class Thread {
115 #pragma warning disable 414             
116                 #region Sync with metadata/object-internals.h
117                 private InternalThread internal_thread;
118                 object m_ThreadStartArg;
119                 private ExecutionContext ec_to_set;
120                 #endregion
121 #pragma warning restore 414
122
123                 IPrincipal principal;
124                 int principal_version;
125                 bool current_culture_set;
126                 bool current_ui_culture_set;
127                 CultureInfo current_culture;
128                 CultureInfo current_ui_culture;
129
130                 // the name of local_slots, current_thread and _ec is
131                 // important because they are used by the runtime.
132                 [ThreadStatic]
133                 static object[] local_slots;
134
135                 [ThreadStatic]
136                 static Thread current_thread;
137
138                 /* The actual ExecutionContext of the thread.  It's
139                    ThreadStatic so that it's not shared between
140                    AppDomains. */
141                 [ThreadStatic]
142                 static ExecutionContext _ec;
143
144                 static internal CultureInfo default_culture;
145                 static internal CultureInfo default_ui_culture;
146
147                 // can be both a ThreadStart and a ParameterizedThreadStart
148                 private MulticastDelegate m_Delegate;
149                 //private string thread_name=null;
150
151                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
152                 private extern void ConstructInternalThread ();
153
154                 private InternalThread Internal {
155                         get {
156                                 if (internal_thread == null)
157                                         ConstructInternalThread ();
158                                 return internal_thread;
159                         }
160                 }
161
162                 public static Context CurrentContext {
163                         [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
164                         get {
165                                 return(AppDomain.InternalGetContext ());
166                         }
167                 }
168
169                 /*
170                  * These two methods return an array in the target
171                  * domain with the same content as the argument.  If
172                  * the argument is already in the target domain, then
173                  * the argument is returned, otherwise a copy.
174                  */
175                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
176                 private extern static byte[] ByteArrayToRootDomain (byte[] arr);
177
178                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
179                 private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
180
181                 static void DeserializePrincipal (Thread th)
182                 {
183                         MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
184                         int type = ms.ReadByte ();
185                         if (type == 0) {
186                                 BinaryFormatter bf = new BinaryFormatter ();
187                                 th.principal = (IPrincipal) bf.Deserialize (ms);
188                                 th.principal_version = th.Internal._serialized_principal_version;
189                         } else if (type == 1) {
190                                 BinaryReader reader = new BinaryReader (ms);
191                                 string name = reader.ReadString ();
192                                 string auth_type = reader.ReadString ();
193                                 int n_roles = reader.ReadInt32 ();
194                                 string [] roles = null;
195                                 if (n_roles >= 0) {
196                                         roles = new string [n_roles];
197                                         for (int i = 0; i < n_roles; i++)
198                                                 roles [i] = reader.ReadString ();
199                                 }
200                                 th.principal = new GenericPrincipal (new GenericIdentity (name, auth_type), roles);
201                         } else if (type == 2 || type == 3) {
202                                 string [] roles = type == 2 ? null : new string [0];
203                                 th.principal = new GenericPrincipal (new GenericIdentity ("", ""), roles);
204                         }
205                 }
206
207                 static void SerializePrincipal (Thread th, IPrincipal value)
208                 {
209                         MemoryStream ms = new MemoryStream ();
210                         bool done = false;
211                         if (value.GetType () == typeof (GenericPrincipal)) {
212                                 GenericPrincipal gp = (GenericPrincipal) value;
213                                 if (gp.Identity != null && gp.Identity.GetType () == typeof (GenericIdentity)) {
214                                         GenericIdentity id = (GenericIdentity) gp.Identity;
215                                         if (id.Name == "" && id.AuthenticationType == "") {
216                                                 if (gp.Roles == null) {
217                                                         ms.WriteByte (2);
218                                                         done = true;
219                                                 } else if (gp.Roles.Length == 0) {
220                                                         ms.WriteByte (3);
221                                                         done = true;
222                                                 }
223                                         } else {
224                                                 ms.WriteByte (1);
225                                                 BinaryWriter br = new BinaryWriter (ms);
226                                                 br.Write (gp.Identity.Name);
227                                                 br.Write (gp.Identity.AuthenticationType);
228                                                 string [] roles = gp.Roles;
229                                                 if  (roles == null) {
230                                                         br.Write ((int) (-1));
231                                                 } else {
232                                                         br.Write (roles.Length);
233                                                         foreach (string s in roles) {
234                                                                 br.Write (s);
235                                                         }
236                                                 }
237                                                 br.Flush ();
238                                                 done = true;
239                                         }
240                                 }
241                         }
242                         if (!done) {
243                                 ms.WriteByte (0);
244                                 BinaryFormatter bf = new BinaryFormatter ();
245                                 try {
246                                         bf.Serialize (ms, value);
247                                 } catch {}
248                         }
249                         th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
250                 }
251
252                 public static IPrincipal CurrentPrincipal {
253                         get {
254                                 Thread th = CurrentThread;
255
256                                 if (th.principal_version != th.Internal._serialized_principal_version)
257                                         th.principal = null;
258
259                                 if (th.principal != null)
260                                         return th.principal;
261
262                                 if (th.Internal._serialized_principal != null) {
263                                         try {
264                                                 DeserializePrincipal (th);
265                                                 return th.principal;
266                                         } catch {}
267                                 }
268
269                                 th.principal = GetDomain ().DefaultPrincipal;
270                                 th.principal_version = th.Internal._serialized_principal_version;
271                                 return th.principal;
272                         }
273                         [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
274                         set {
275                                 Thread th = CurrentThread;
276
277                                 if (value != GetDomain ().DefaultPrincipal) {
278                                         ++th.Internal._serialized_principal_version;
279                                         try {
280                                                 SerializePrincipal (th, value);
281                                         } catch (Exception) {
282                                                 th.Internal._serialized_principal = null;
283                                         }
284                                         th.principal_version = th.Internal._serialized_principal_version;
285                                 } else {
286                                         th.Internal._serialized_principal = null;
287                                 }
288
289                                 th.principal = value;
290                         }
291                 }
292
293                 // Looks up the object associated with the current thread
294                 // this is called by the JIT directly, too
295                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
296                 private extern static InternalThread CurrentInternalThread_internal();
297
298                 public static Thread CurrentThread {
299                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
300                         get {
301                                 if (current_thread == null)
302                                         current_thread = new Thread (CurrentInternalThread_internal ());
303                                 return current_thread;
304                         }
305                 }
306
307                 internal static int CurrentThreadId {
308                         get {
309                                 return (int)(CurrentThread.internal_thread.thread_id);
310                         }
311                 }
312
313                 public static AppDomain GetDomain() {
314                         return AppDomain.CurrentDomain;
315                 }
316
317                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
318                 public extern static int GetDomainID();
319
320                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
321                 private extern static void ResetAbort_internal();
322
323                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
324                 public static void ResetAbort ()
325                 {
326                         ResetAbort_internal ();
327                 }
328
329                 [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
330                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
331                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
332                 public extern static bool Yield ();
333
334
335                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
336                 private extern static void Sleep_internal(int ms);
337
338                 public static void Sleep (int millisecondsTimeout)
339                 {
340                         if (millisecondsTimeout < Timeout.Infinite)
341                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
342
343                         Sleep_internal (millisecondsTimeout);
344                 }
345
346                 public static void Sleep (TimeSpan timeout)
347                 {
348                         long ms = (long) timeout.TotalMilliseconds;
349                         if (ms < Timeout.Infinite || ms > Int32.MaxValue)
350                                 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
351
352                         Sleep_internal ((int) ms);
353                 }
354
355                 // Returns the system thread handle
356                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
357                 private extern IntPtr Thread_internal (MulticastDelegate start);
358
359                 public Thread(ThreadStart start) {
360                         if(start==null) {
361                                 throw new ArgumentNullException("Null ThreadStart");
362                         }
363                         m_Delegate=start;
364                 }
365
366                 private Thread (InternalThread it) {
367                         internal_thread = it;
368                 }
369                 
370                 // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
371                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
372                 ~Thread ()
373                 {
374                 }
375
376                 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
377                 public ApartmentState ApartmentState {
378                         get {
379                                 if ((ThreadState & ThreadState.Stopped) != 0)
380                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
381
382                                 return (ApartmentState)Internal.apartment_state;
383                         }
384
385                         set {
386                                 TrySetApartmentState (value);
387                         }
388                 }
389
390                 //[MethodImplAttribute (MethodImplOptions.InternalCall)]
391                 //private static extern int current_lcid ();
392
393                 public CultureInfo CurrentCulture {
394                         get {
395                                 CultureInfo culture = current_culture;
396                                 if (current_culture_set && culture != null)
397                                         return culture;
398
399                                 if (default_culture != null)
400                                         return default_culture;
401
402                                 current_culture = culture = CultureInfo.ConstructCurrentCulture ();
403                                 return culture;
404                         }
405                         
406                         [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
407                         set {
408                                 if (value == null)
409                                         throw new ArgumentNullException ("value");
410
411                                 value.CheckNeutral ();
412                                 current_culture = value;
413                                 current_culture_set = true;
414                         }
415                 }
416
417                 public CultureInfo CurrentUICulture {
418                         get {
419                                 CultureInfo culture = current_ui_culture;
420                                 if (current_ui_culture_set && culture != null)
421                                         return culture;
422
423                                 if (default_ui_culture != null)
424                                         return default_ui_culture;
425
426                                 current_ui_culture = culture = CultureInfo.ConstructCurrentUICulture ();
427                                 return culture;
428                         }
429                         
430                         set {
431                                 if (value == null)
432                                         throw new ArgumentNullException ("value");
433                                 current_ui_culture = value;
434                                 current_ui_culture_set = true;
435                         }
436                 }
437
438                 public bool IsThreadPoolThread {
439                         get {
440                                 return IsThreadPoolThreadInternal;
441                         }
442                 }
443
444                 internal bool IsThreadPoolThreadInternal {
445                         get {
446                                 return Internal.threadpool_thread;
447                         }
448                         set {
449                                 Internal.threadpool_thread = value;
450                         }
451                 }
452
453                 public bool IsAlive {
454                         get {
455                                 ThreadState curstate = GetState (Internal);
456                                 
457                                 if((curstate & ThreadState.Aborted) != 0 ||
458                                    (curstate & ThreadState.Stopped) != 0 ||
459                                    (curstate & ThreadState.Unstarted) != 0) {
460                                         return(false);
461                                 } else {
462                                         return(true);
463                                 }
464                         }
465                 }
466
467                 public bool IsBackground {
468                         get {
469                                 ThreadState thread_state = GetState (Internal);
470                                 if ((thread_state & ThreadState.Stopped) != 0)
471                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
472
473                                 return (thread_state & ThreadState.Background) != 0;
474                         }
475                         
476                         set {
477                                 if (value) {
478                                         SetState (Internal, ThreadState.Background);
479                                 } else {
480                                         ClrState (Internal, ThreadState.Background);
481                                 }
482                         }
483                 }
484
485                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
486                 private extern static string GetName_internal (InternalThread thread);
487
488                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
489                 private extern static void SetName_internal (InternalThread thread, String name);
490
491                 /* 
492                  * The thread name must be shared by appdomains, so it is stored in
493                  * unmanaged code.
494                  */
495
496                 public string Name {
497                         get {
498                                 return GetName_internal (Internal);
499                         }
500                         
501                         set {
502                                 SetName_internal (Internal, value);
503                         }
504                 }
505
506                 public ThreadPriority Priority {
507                         get {
508                                 return (ThreadPriority)GetPriority (Internal);
509                         }
510                         
511                         set {
512                                 // FIXME: This doesn't do anything yet
513                                 SetPriority (Internal, (int)value);
514                         }
515                 }
516
517                 public ThreadState ThreadState {
518                         get {
519                                 return GetState (Internal);
520                         }
521                 }
522
523                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
524                 private extern static void Abort_internal (InternalThread thread, object stateInfo);
525
526                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
527                 private extern static int GetPriority (InternalThread thread);
528
529                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
530                 private extern static void SetPriority (InternalThread thread, int priority);
531
532                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
533                 public void Abort () 
534                 {
535                         Abort_internal (Internal, null);
536                 }
537
538                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
539                 public void Abort (object stateInfo) 
540                 {
541                         Abort_internal (Internal, stateInfo);
542                 }
543
544                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
545                 extern object GetAbortExceptionState ();
546
547                 internal object AbortReason {
548                         get {
549                                 return GetAbortExceptionState ();
550                         }
551                 }
552
553                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
554                 private extern static void Interrupt_internal (InternalThread thread);
555                 
556                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
557                 public void Interrupt ()
558                 {
559                         Interrupt_internal (Internal);
560                 }
561
562                 // The current thread joins with 'this'. Set ms to 0 to block
563                 // until this actually exits.
564                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
565                 private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
566                 
567                 public void Join()
568                 {
569                         Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
570                 }
571
572                 public bool Join(int millisecondsTimeout)
573                 {
574                         if (millisecondsTimeout < Timeout.Infinite)
575                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
576
577                         return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
578                 }
579
580                 public bool Join(TimeSpan timeout)
581                 {
582                         long ms = (long) timeout.TotalMilliseconds;
583                         if (ms < Timeout.Infinite || ms > Int32.MaxValue)
584                                 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
585
586                         return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
587                 }
588
589                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
590                 public extern static void MemoryBarrier ();
591
592                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
593                 private extern void Resume_internal();
594
595                 [Obsolete ("")]
596                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
597                 public void Resume () 
598                 {
599                         Resume_internal ();
600                 }
601
602                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
603                 private extern static void SpinWait_nop ();
604
605
606                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
607                 public static void SpinWait (int iterations) 
608                 {
609                         if (iterations < 0)
610                                 return;
611                         while (iterations-- > 0)
612                         {
613                                 SpinWait_nop ();
614                         }
615                 }
616
617                 private void StartInternal ()
618                 {
619                         current_thread = this;
620
621                         if (m_Delegate is ThreadStart) {
622                                 ((ThreadStart) m_Delegate) ();
623                         } else {
624                                 ((ParameterizedThreadStart) m_Delegate) (m_ThreadStartArg);
625                         }
626                 }
627
628                 public void Start() {
629                         // propagate informations from the original thread to the new thread
630                         ec_to_set = ExecutionContext.Capture (false, true);
631                         Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
632
633                         // Thread_internal creates and starts the new thread, 
634                         if (Thread_internal((ThreadStart) StartInternal) == (IntPtr) 0)
635                                 throw new SystemException ("Thread creation failed.");
636                 }
637
638                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
639                 private extern static void Suspend_internal(InternalThread thread);
640
641                 [Obsolete ("")]
642                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
643                 public void Suspend ()
644                 {
645                         Suspend_internal (Internal);
646                 }
647
648                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
649                 extern private static void SetState (InternalThread thread, ThreadState set);
650
651                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
652                 extern private static void ClrState (InternalThread thread, ThreadState clr);
653
654                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
655                 extern private static ThreadState GetState (InternalThread thread);
656
657                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
658                 extern public static byte VolatileRead (ref byte address);
659                 
660                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
661                 extern public static double VolatileRead (ref double address);
662                 
663                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
664                 extern public static short VolatileRead (ref short address);
665                 
666                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
667                 extern public static int VolatileRead (ref int address);
668                 
669                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
670                 extern public static long VolatileRead (ref long address);
671                 
672                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
673                 extern public static IntPtr VolatileRead (ref IntPtr address);
674                 
675                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
676                 extern public static object VolatileRead (ref object address);
677
678                 [CLSCompliant(false)]
679                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
680                 extern public static sbyte VolatileRead (ref sbyte address);
681                 
682                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
683                 extern public static float VolatileRead (ref float address);
684
685                 [CLSCompliant (false)]
686                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
687                 extern public static ushort VolatileRead (ref ushort address);
688
689                 [CLSCompliant (false)]
690                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
691                 extern public static uint VolatileRead (ref uint address);
692
693                 [CLSCompliant (false)]
694                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
695                 extern public static ulong VolatileRead (ref ulong address);
696
697                 [CLSCompliant (false)]
698                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
699                 extern public static UIntPtr VolatileRead (ref UIntPtr address);
700
701                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
702                 extern public static void VolatileWrite (ref byte address, byte value);
703                 
704                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
705                 extern public static void VolatileWrite (ref double address, double value);
706                 
707                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
708                 extern public static void VolatileWrite (ref short address, short value);
709                 
710                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
711                 extern public static void VolatileWrite (ref int address, int value);
712                 
713                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
714                 extern public static void VolatileWrite (ref long address, long value);
715                 
716                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
717                 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
718                 
719                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
720                 extern public static void VolatileWrite (ref object address, object value);
721
722                 [CLSCompliant(false)]
723                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
724                 extern public static void VolatileWrite (ref sbyte address, sbyte value);
725                 
726                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
727                 extern public static void VolatileWrite (ref float address, float value);
728
729                 [CLSCompliant (false)]
730                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
731                 extern public static void VolatileWrite (ref ushort address, ushort value);
732
733                 [CLSCompliant (false)]
734                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
735                 extern public static void VolatileWrite (ref uint address, uint value);
736
737                 [CLSCompliant (false)]
738                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
739                 extern public static void VolatileWrite (ref ulong address, ulong value);
740
741                 [CLSCompliant (false)]
742                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
743                 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
744                 
745                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
746                 extern static int SystemMaxStackStize ();
747
748                 static int GetProcessDefaultStackSize (int maxStackSize)
749                 {
750                         if (maxStackSize < 131072) // make sure stack is at least 128k big
751                                 return 131072;
752
753                         int page_size = Environment.GetPageSize ();
754
755                         if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
756                                 maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
757
758                         /* Respect the max stack size imposed by the system*/
759                         return Math.Min (maxStackSize, SystemMaxStackStize ());
760                 }
761
762                 void SetStart (MulticastDelegate start, int maxStackSize)
763                 {
764                         m_Delegate = start;
765                         Internal.stack_size = maxStackSize;
766                 }
767
768                 public ExecutionContext ExecutionContext {
769                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
770                         get {
771                                 if (_ec == null)
772                                         _ec = new ExecutionContext ();
773                                 return _ec;
774                         }
775                         internal set {
776                                 _ec = value;
777                         }
778                 }
779
780                 internal bool HasExecutionContext {
781                         get {
782                                 return _ec != null;
783                         }
784                 }
785
786                 public int ManagedThreadId {
787                         [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
788                         get {
789                                 return Internal.managed_id;
790                         }
791                 }
792
793                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
794                 public static void BeginCriticalRegion ()
795                 {
796                         CurrentThread.Internal.critical_region_level++;
797                 }
798
799                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
800                 public static void EndCriticalRegion ()
801                 {
802                         CurrentThread.Internal.critical_region_level--;
803                 }
804
805                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
806                 public static void BeginThreadAffinity ()
807                 {
808                         // Managed and native threads are currently bound together.
809                 }
810
811                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
812                 public static void EndThreadAffinity ()
813                 {
814                         // Managed and native threads are currently bound together.
815                 }
816
817                 public ApartmentState GetApartmentState ()
818                 {
819                         return (ApartmentState)Internal.apartment_state;
820                 }
821
822                 public void SetApartmentState (ApartmentState state)
823                 {
824                         if (!TrySetApartmentState (state))
825                                 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
826                 }
827
828                 public bool TrySetApartmentState (ApartmentState state) 
829                 {
830                         if ((ThreadState & ThreadState.Unstarted) == 0)
831                                 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
832
833                         if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown && 
834                             (ApartmentState)Internal.apartment_state != state)
835                                 return false;
836
837                         Internal.apartment_state = (byte)state;
838
839                         return true;
840                 }
841                 
842                 [ComVisible (false)]
843                 public override int GetHashCode ()
844                 {
845                         return ManagedThreadId;
846                 }
847
848                 public void Start (object parameter)
849                 {
850                         m_ThreadStartArg = parameter;
851                         Start ();
852                 }
853
854                 internal CultureInfo GetCurrentUICultureNoAppX ()
855                 {
856                         return CultureInfo.CurrentUICulture;
857                 }
858         }
859 }