[MSBuild] Fix minor assembly resolution issue
[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                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
299                 internal extern static uint AllocTlsData (Type type);
300
301                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
302                 internal extern static void DestroyTlsData (uint offset);
303
304                 public static Thread CurrentThread {
305                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
306                         get {
307                                 if (current_thread == null)
308                                         current_thread = new Thread (CurrentInternalThread_internal ());
309                                 return current_thread;
310                         }
311                 }
312
313                 internal static int CurrentThreadId {
314                         get {
315                                 return (int)(CurrentThread.internal_thread.thread_id);
316                         }
317                 }
318
319                 public static AppDomain GetDomain() {
320                         return AppDomain.CurrentDomain;
321                 }
322
323                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
324                 public extern static int GetDomainID();
325
326                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
327                 private extern static void ResetAbort_internal();
328
329                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
330                 public static void ResetAbort ()
331                 {
332                         ResetAbort_internal ();
333                 }
334
335                 [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
336                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
337                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
338                 public extern static bool Yield ();
339
340
341                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
342                 private extern static void Sleep_internal(int ms);
343
344                 public static void Sleep (int millisecondsTimeout)
345                 {
346                         if (millisecondsTimeout < Timeout.Infinite)
347                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
348
349                         Sleep_internal (millisecondsTimeout);
350                 }
351
352                 public static void Sleep (TimeSpan timeout)
353                 {
354                         long ms = (long) timeout.TotalMilliseconds;
355                         if (ms < Timeout.Infinite || ms > Int32.MaxValue)
356                                 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
357
358                         Sleep_internal ((int) ms);
359                 }
360
361                 // Returns the system thread handle
362                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
363                 private extern IntPtr Thread_internal (MulticastDelegate start);
364
365                 public Thread(ThreadStart start) {
366                         if(start==null) {
367                                 throw new ArgumentNullException("Null ThreadStart");
368                         }
369                         m_Delegate=start;
370                 }
371
372                 private Thread (InternalThread it) {
373                         internal_thread = it;
374                 }
375                 
376                 // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
377                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
378                 ~Thread ()
379                 {
380                 }
381
382                 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
383                 public ApartmentState ApartmentState {
384                         get {
385                                 if ((ThreadState & ThreadState.Stopped) != 0)
386                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
387
388                                 return (ApartmentState)Internal.apartment_state;
389                         }
390
391                         set {
392                                 TrySetApartmentState (value);
393                         }
394                 }
395
396                 //[MethodImplAttribute (MethodImplOptions.InternalCall)]
397                 //private static extern int current_lcid ();
398
399                 public CultureInfo CurrentCulture {
400                         get {
401                                 CultureInfo culture = current_culture;
402                                 if (current_culture_set && culture != null)
403                                         return culture;
404
405                                 if (default_culture != null)
406                                         return default_culture;
407
408                                 current_culture = culture = CultureInfo.ConstructCurrentCulture ();
409                                 return culture;
410                         }
411                         
412                         [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
413                         set {
414                                 if (value == null)
415                                         throw new ArgumentNullException ("value");
416
417                                 value.CheckNeutral ();
418                                 current_culture = value;
419                                 current_culture_set = true;
420                         }
421                 }
422
423                 public CultureInfo CurrentUICulture {
424                         get {
425                                 CultureInfo culture = current_ui_culture;
426                                 if (current_ui_culture_set && culture != null)
427                                         return culture;
428
429                                 if (default_ui_culture != null)
430                                         return default_ui_culture;
431
432                                 current_ui_culture = culture = CultureInfo.ConstructCurrentUICulture ();
433                                 return culture;
434                         }
435                         
436                         set {
437                                 if (value == null)
438                                         throw new ArgumentNullException ("value");
439                                 current_ui_culture = value;
440                                 current_ui_culture_set = true;
441                         }
442                 }
443
444                 public bool IsThreadPoolThread {
445                         get {
446                                 return IsThreadPoolThreadInternal;
447                         }
448                 }
449
450                 internal bool IsThreadPoolThreadInternal {
451                         get {
452                                 return Internal.threadpool_thread;
453                         }
454                         set {
455                                 Internal.threadpool_thread = value;
456                         }
457                 }
458
459                 public bool IsAlive {
460                         get {
461                                 ThreadState curstate = GetState (Internal);
462                                 
463                                 if((curstate & ThreadState.Aborted) != 0 ||
464                                    (curstate & ThreadState.Stopped) != 0 ||
465                                    (curstate & ThreadState.Unstarted) != 0) {
466                                         return(false);
467                                 } else {
468                                         return(true);
469                                 }
470                         }
471                 }
472
473                 public bool IsBackground {
474                         get {
475                                 ThreadState thread_state = GetState (Internal);
476                                 if ((thread_state & ThreadState.Stopped) != 0)
477                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
478
479                                 return (thread_state & ThreadState.Background) != 0;
480                         }
481                         
482                         set {
483                                 if (value) {
484                                         SetState (Internal, ThreadState.Background);
485                                 } else {
486                                         ClrState (Internal, ThreadState.Background);
487                                 }
488                         }
489                 }
490
491                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
492                 private extern static string GetName_internal (InternalThread thread);
493
494                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
495                 private extern static void SetName_internal (InternalThread thread, String name);
496
497                 /* 
498                  * The thread name must be shared by appdomains, so it is stored in
499                  * unmanaged code.
500                  */
501
502                 public string Name {
503                         get {
504                                 return GetName_internal (Internal);
505                         }
506                         
507                         set {
508                                 SetName_internal (Internal, value);
509                         }
510                 }
511
512                 public ThreadPriority Priority {
513                         get {
514                                 return (ThreadPriority)GetPriority (Internal);
515                         }
516                         
517                         set {
518                                 // FIXME: This doesn't do anything yet
519                                 SetPriority (Internal, (int)value);
520                         }
521                 }
522
523                 public ThreadState ThreadState {
524                         get {
525                                 return GetState (Internal);
526                         }
527                 }
528
529                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
530                 private extern static void Abort_internal (InternalThread thread, object stateInfo);
531
532                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
533                 private extern static int GetPriority (InternalThread thread);
534
535                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
536                 private extern static void SetPriority (InternalThread thread, int priority);
537
538                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
539                 public void Abort () 
540                 {
541                         Abort_internal (Internal, null);
542                 }
543
544                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
545                 public void Abort (object stateInfo) 
546                 {
547                         Abort_internal (Internal, stateInfo);
548                 }
549
550                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
551                 extern object GetAbortExceptionState ();
552
553                 internal object AbortReason {
554                         get {
555                                 return GetAbortExceptionState ();
556                         }
557                 }
558
559                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
560                 private extern static void Interrupt_internal (InternalThread thread);
561                 
562                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
563                 public void Interrupt ()
564                 {
565                         Interrupt_internal (Internal);
566                 }
567
568                 // The current thread joins with 'this'. Set ms to 0 to block
569                 // until this actually exits.
570                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
571                 private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
572                 
573                 public void Join()
574                 {
575                         Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
576                 }
577
578                 public bool Join(int millisecondsTimeout)
579                 {
580                         if (millisecondsTimeout < Timeout.Infinite)
581                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
582
583                         return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
584                 }
585
586                 public bool Join(TimeSpan timeout)
587                 {
588                         long ms = (long) timeout.TotalMilliseconds;
589                         if (ms < Timeout.Infinite || ms > Int32.MaxValue)
590                                 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
591
592                         return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
593                 }
594
595                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
596                 public extern static void MemoryBarrier ();
597
598                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
599                 private extern void Resume_internal();
600
601                 [Obsolete ("")]
602                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
603                 public void Resume () 
604                 {
605                         Resume_internal ();
606                 }
607
608                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
609                 private extern static void SpinWait_nop ();
610
611
612                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
613                 public static void SpinWait (int iterations) 
614                 {
615                         if (iterations < 0)
616                                 return;
617                         while (iterations-- > 0)
618                         {
619                                 SpinWait_nop ();
620                         }
621                 }
622
623                 private void StartInternal ()
624                 {
625                         current_thread = this;
626
627                         if (m_Delegate is ThreadStart) {
628                                 ((ThreadStart) m_Delegate) ();
629                         } else {
630                                 ((ParameterizedThreadStart) m_Delegate) (m_ThreadStartArg);
631                         }
632                 }
633
634                 public void Start() {
635                         // propagate informations from the original thread to the new thread
636                         ec_to_set = ExecutionContext.Capture (false, true);
637                         Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
638
639                         // Thread_internal creates and starts the new thread, 
640                         if (Thread_internal((ThreadStart) StartInternal) == (IntPtr) 0)
641                                 throw new SystemException ("Thread creation failed.");
642                 }
643
644                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
645                 private extern static void Suspend_internal(InternalThread thread);
646
647                 [Obsolete ("")]
648                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
649                 public void Suspend ()
650                 {
651                         Suspend_internal (Internal);
652                 }
653
654                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
655                 extern private static void SetState (InternalThread thread, ThreadState set);
656
657                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
658                 extern private static void ClrState (InternalThread thread, ThreadState clr);
659
660                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
661                 extern private static ThreadState GetState (InternalThread thread);
662
663                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
664                 extern public static byte VolatileRead (ref byte address);
665                 
666                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
667                 extern public static double VolatileRead (ref double address);
668                 
669                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
670                 extern public static short VolatileRead (ref short address);
671                 
672                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
673                 extern public static int VolatileRead (ref int address);
674                 
675                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
676                 extern public static long VolatileRead (ref long address);
677                 
678                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
679                 extern public static IntPtr VolatileRead (ref IntPtr address);
680                 
681                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
682                 extern public static object VolatileRead (ref object address);
683
684                 [CLSCompliant(false)]
685                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
686                 extern public static sbyte VolatileRead (ref sbyte address);
687                 
688                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
689                 extern public static float VolatileRead (ref float address);
690
691                 [CLSCompliant (false)]
692                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
693                 extern public static ushort VolatileRead (ref ushort address);
694
695                 [CLSCompliant (false)]
696                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
697                 extern public static uint VolatileRead (ref uint address);
698
699                 [CLSCompliant (false)]
700                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
701                 extern public static ulong VolatileRead (ref ulong address);
702
703                 [CLSCompliant (false)]
704                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
705                 extern public static UIntPtr VolatileRead (ref UIntPtr address);
706
707                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
708                 extern public static void VolatileWrite (ref byte address, byte value);
709                 
710                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
711                 extern public static void VolatileWrite (ref double address, double value);
712                 
713                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
714                 extern public static void VolatileWrite (ref short address, short value);
715                 
716                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
717                 extern public static void VolatileWrite (ref int address, int value);
718                 
719                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
720                 extern public static void VolatileWrite (ref long address, long value);
721                 
722                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
723                 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
724                 
725                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
726                 extern public static void VolatileWrite (ref object address, object value);
727
728                 [CLSCompliant(false)]
729                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
730                 extern public static void VolatileWrite (ref sbyte address, sbyte value);
731                 
732                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
733                 extern public static void VolatileWrite (ref float address, float value);
734
735                 [CLSCompliant (false)]
736                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
737                 extern public static void VolatileWrite (ref ushort address, ushort value);
738
739                 [CLSCompliant (false)]
740                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
741                 extern public static void VolatileWrite (ref uint address, uint value);
742
743                 [CLSCompliant (false)]
744                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
745                 extern public static void VolatileWrite (ref ulong address, ulong value);
746
747                 [CLSCompliant (false)]
748                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
749                 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
750                 
751                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
752                 extern static int SystemMaxStackStize ();
753
754                 static int GetProcessDefaultStackSize (int maxStackSize)
755                 {
756                         if (maxStackSize < 131072) // make sure stack is at least 128k big
757                                 return 131072;
758
759                         int page_size = Environment.GetPageSize ();
760
761                         if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
762                                 maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
763
764                         /* Respect the max stack size imposed by the system*/
765                         return Math.Min (maxStackSize, SystemMaxStackStize ());
766                 }
767
768                 void SetStart (MulticastDelegate start, int maxStackSize)
769                 {
770                         m_Delegate = start;
771                         Internal.stack_size = maxStackSize;
772                 }
773
774                 public ExecutionContext ExecutionContext {
775                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
776                         get {
777                                 if (_ec == null)
778                                         _ec = new ExecutionContext ();
779                                 return _ec;
780                         }
781                         internal set {
782                                 _ec = value;
783                         }
784                 }
785
786                 internal bool HasExecutionContext {
787                         get {
788                                 return _ec != null;
789                         }
790                 }
791
792                 internal void BranchExecutionContext (out ExecutionContext.Switcher switcher)
793                 {
794                         if (_ec == null) {
795                                 switcher =  new ExecutionContext.Switcher ();
796                         } else {
797                                 switcher = new ExecutionContext.Switcher (_ec);
798                                 _ec.CopyOnWrite = true;
799                         }
800                 }
801
802                 internal void RestoreExecutionContext (ref ExecutionContext.Switcher switcher)
803                 {
804                         if (switcher.IsEmpty) {
805                                 _ec = null;
806                                 return;
807                         }
808
809                         switcher.Restore (_ec);
810                 }
811
812                 public int ManagedThreadId {
813                         [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
814                         get {
815                                 return Internal.managed_id;
816                         }
817                 }
818
819                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
820                 public static void BeginCriticalRegion ()
821                 {
822                         CurrentThread.Internal.critical_region_level++;
823                 }
824
825                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
826                 public static void EndCriticalRegion ()
827                 {
828                         CurrentThread.Internal.critical_region_level--;
829                 }
830
831                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
832                 public static void BeginThreadAffinity ()
833                 {
834                         // Managed and native threads are currently bound together.
835                 }
836
837                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
838                 public static void EndThreadAffinity ()
839                 {
840                         // Managed and native threads are currently bound together.
841                 }
842
843                 public ApartmentState GetApartmentState ()
844                 {
845                         return (ApartmentState)Internal.apartment_state;
846                 }
847
848                 public void SetApartmentState (ApartmentState state)
849                 {
850                         if (!TrySetApartmentState (state))
851                                 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
852                 }
853
854                 public bool TrySetApartmentState (ApartmentState state) 
855                 {
856                         if ((ThreadState & ThreadState.Unstarted) == 0)
857                                 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
858
859                         if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown && 
860                             (ApartmentState)Internal.apartment_state != state)
861                                 return false;
862
863                         Internal.apartment_state = (byte)state;
864
865                         return true;
866                 }
867                 
868                 [ComVisible (false)]
869                 public override int GetHashCode ()
870                 {
871                         return ManagedThreadId;
872                 }
873
874                 public void Start (object parameter)
875                 {
876                         m_ThreadStartArg = parameter;
877                         Start ();
878                 }
879
880                 internal CultureInfo GetCurrentUICultureNoAppX ()
881                 {
882                         return CultureInfo.CurrentUICulture;
883                 }
884         }
885 }