6bcb53a60581a649587a9e6e0b91dc59c0fe136f
[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 NamedDataSlot namedDataSlot;             
145
146                 static internal CultureInfo default_culture;
147                 static internal CultureInfo default_ui_culture;
148
149                 // can be both a ThreadStart and a ParameterizedThreadStart
150                 private MulticastDelegate m_Delegate;
151                 //private string thread_name=null;
152
153                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
154                 private extern void ConstructInternalThread ();
155
156                 private InternalThread Internal {
157                         get {
158                                 if (internal_thread == null)
159                                         ConstructInternalThread ();
160                                 return internal_thread;
161                         }
162                 }
163
164                 public static Context CurrentContext {
165                         [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
166                         get {
167                                 return(AppDomain.InternalGetContext ());
168                         }
169                 }
170
171                 /*
172                  * These two methods return an array in the target
173                  * domain with the same content as the argument.  If
174                  * the argument is already in the target domain, then
175                  * the argument is returned, otherwise a copy.
176                  */
177                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
178                 private extern static byte[] ByteArrayToRootDomain (byte[] arr);
179
180                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
181                 private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
182
183                 static void DeserializePrincipal (Thread th)
184                 {
185                         MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
186                         int type = ms.ReadByte ();
187                         if (type == 0) {
188                                 BinaryFormatter bf = new BinaryFormatter ();
189                                 th.principal = (IPrincipal) bf.Deserialize (ms);
190                                 th.principal_version = th.Internal._serialized_principal_version;
191                         } else if (type == 1) {
192                                 BinaryReader reader = new BinaryReader (ms);
193                                 string name = reader.ReadString ();
194                                 string auth_type = reader.ReadString ();
195                                 int n_roles = reader.ReadInt32 ();
196                                 string [] roles = null;
197                                 if (n_roles >= 0) {
198                                         roles = new string [n_roles];
199                                         for (int i = 0; i < n_roles; i++)
200                                                 roles [i] = reader.ReadString ();
201                                 }
202                                 th.principal = new GenericPrincipal (new GenericIdentity (name, auth_type), roles);
203                         } else if (type == 2 || type == 3) {
204                                 string [] roles = type == 2 ? null : new string [0];
205                                 th.principal = new GenericPrincipal (new GenericIdentity ("", ""), roles);
206                         }
207                 }
208
209                 static void SerializePrincipal (Thread th, IPrincipal value)
210                 {
211                         MemoryStream ms = new MemoryStream ();
212                         bool done = false;
213                         if (value.GetType () == typeof (GenericPrincipal)) {
214                                 GenericPrincipal gp = (GenericPrincipal) value;
215                                 if (gp.Identity != null && gp.Identity.GetType () == typeof (GenericIdentity)) {
216                                         GenericIdentity id = (GenericIdentity) gp.Identity;
217                                         if (id.Name == "" && id.AuthenticationType == "") {
218                                                 if (gp.Roles == null) {
219                                                         ms.WriteByte (2);
220                                                         done = true;
221                                                 } else if (gp.Roles.Length == 0) {
222                                                         ms.WriteByte (3);
223                                                         done = true;
224                                                 }
225                                         } else {
226                                                 ms.WriteByte (1);
227                                                 BinaryWriter br = new BinaryWriter (ms);
228                                                 br.Write (gp.Identity.Name);
229                                                 br.Write (gp.Identity.AuthenticationType);
230                                                 string [] roles = gp.Roles;
231                                                 if  (roles == null) {
232                                                         br.Write ((int) (-1));
233                                                 } else {
234                                                         br.Write (roles.Length);
235                                                         foreach (string s in roles) {
236                                                                 br.Write (s);
237                                                         }
238                                                 }
239                                                 br.Flush ();
240                                                 done = true;
241                                         }
242                                 }
243                         }
244                         if (!done) {
245                                 ms.WriteByte (0);
246                                 BinaryFormatter bf = new BinaryFormatter ();
247                                 try {
248                                         bf.Serialize (ms, value);
249                                 } catch {}
250                         }
251                         th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
252                 }
253
254                 public static IPrincipal CurrentPrincipal {
255                         get {
256                                 Thread th = CurrentThread;
257
258                                 if (th.principal_version != th.Internal._serialized_principal_version)
259                                         th.principal = null;
260
261                                 if (th.principal != null)
262                                         return th.principal;
263
264                                 if (th.Internal._serialized_principal != null) {
265                                         try {
266                                                 DeserializePrincipal (th);
267                                                 return th.principal;
268                                         } catch {}
269                                 }
270
271                                 th.principal = GetDomain ().DefaultPrincipal;
272                                 th.principal_version = th.Internal._serialized_principal_version;
273                                 return th.principal;
274                         }
275                         [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
276                         set {
277                                 Thread th = CurrentThread;
278
279                                 if (value != GetDomain ().DefaultPrincipal) {
280                                         ++th.Internal._serialized_principal_version;
281                                         try {
282                                                 SerializePrincipal (th, value);
283                                         } catch (Exception) {
284                                                 th.Internal._serialized_principal = null;
285                                         }
286                                         th.principal_version = th.Internal._serialized_principal_version;
287                                 } else {
288                                         th.Internal._serialized_principal = null;
289                                 }
290
291                                 th.principal = value;
292                         }
293                 }
294
295                 // Looks up the object associated with the current thread
296                 // this is called by the JIT directly, too
297                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
298                 private extern static InternalThread CurrentInternalThread_internal();
299
300                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
301                 internal extern static uint AllocTlsData (Type type);
302
303                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
304                 internal extern static void DestroyTlsData (uint offset);
305
306                 public static Thread CurrentThread {
307                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
308                         get {
309                                 if (current_thread == null)
310                                         current_thread = new Thread (CurrentInternalThread_internal ());
311                                 return current_thread;
312                         }
313                 }
314
315                 internal static int CurrentThreadId {
316                         get {
317                                 return (int)(CurrentThread.internal_thread.thread_id);
318                         }
319                 }
320                 
321                 static NamedDataSlot NamedDataSlot {
322                         get {
323                                 if (namedDataSlot == null)
324                                         Interlocked.CompareExchange (ref namedDataSlot, new NamedDataSlot (true), null);
325
326                                 return namedDataSlot;
327                         }
328                 }
329                 
330                 public static LocalDataStoreSlot AllocateNamedDataSlot (string name)
331                 {
332                         return NamedDataSlot.Allocate (name);
333                 }
334
335                 public static void FreeNamedDataSlot (string name)
336                 {
337                         NamedDataSlot.Free (name);
338                 }
339
340                 public static LocalDataStoreSlot AllocateDataSlot ()
341                 {
342                         return new LocalDataStoreSlot (true);
343                 }
344
345                 public static object GetData (LocalDataStoreSlot slot) {
346                         object[] slots = local_slots;
347                         if (slot == null)
348                                 throw new ArgumentNullException ("slot");
349                         if (slots != null && slot.slot < slots.Length)
350                                 return slots [slot.slot];
351                         return null;
352                 }
353
354                 public static void SetData (LocalDataStoreSlot slot, object data) {
355                         object[] slots = local_slots;
356                         if (slot == null)
357                                 throw new ArgumentNullException ("slot");
358                         if (slots == null) {
359                                 slots = new object [slot.slot + 2];
360                                 local_slots = slots;
361                         } else if (slot.slot >= slots.Length) {
362                                 object[] nslots = new object [slot.slot + 2];
363                                 slots.CopyTo (nslots, 0);
364                                 slots = nslots;
365                                 local_slots = slots;
366                         }
367                         slots [slot.slot] = data;
368                 }
369
370                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
371                 internal extern static void FreeLocalSlotValues (int slot, bool thread_local);
372
373                 public static LocalDataStoreSlot GetNamedDataSlot(string name)
374                 {
375                         return NamedDataSlot.Get (name);
376                 }
377                 
378                 public static AppDomain GetDomain() {
379                         return AppDomain.CurrentDomain;
380                 }
381
382                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
383                 public extern static int GetDomainID();
384
385                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
386                 private extern static void ResetAbort_internal();
387
388                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
389                 public static void ResetAbort ()
390                 {
391                         ResetAbort_internal ();
392                 }
393
394                 [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
395                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
396                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
397                 public extern static bool Yield ();
398
399
400                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
401                 private extern static void Sleep_internal(int ms);
402
403                 public static void Sleep (int millisecondsTimeout)
404                 {
405                         if (millisecondsTimeout < Timeout.Infinite)
406                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
407
408                         Sleep_internal (millisecondsTimeout);
409                 }
410
411                 public static void Sleep (TimeSpan timeout)
412                 {
413                         long ms = (long) timeout.TotalMilliseconds;
414                         if (ms < Timeout.Infinite || ms > Int32.MaxValue)
415                                 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
416
417                         Sleep_internal ((int) ms);
418                 }
419
420                 // Returns the system thread handle
421                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
422                 private extern IntPtr Thread_internal (MulticastDelegate start);
423
424                 public Thread(ThreadStart start) {
425                         if(start==null) {
426                                 throw new ArgumentNullException("Null ThreadStart");
427                         }
428                         m_Delegate=start;
429                 }
430
431                 private Thread (InternalThread it) {
432                         internal_thread = it;
433                 }
434                 
435                 // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
436                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
437                 ~Thread ()
438                 {
439                 }
440
441                 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
442                 public ApartmentState ApartmentState {
443                         get {
444                                 if ((ThreadState & ThreadState.Stopped) != 0)
445                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
446
447                                 return (ApartmentState)Internal.apartment_state;
448                         }
449
450                         set {
451                                 TrySetApartmentState (value);
452                         }
453                 }
454
455                 //[MethodImplAttribute (MethodImplOptions.InternalCall)]
456                 //private static extern int current_lcid ();
457
458                 public CultureInfo CurrentCulture {
459                         get {
460                                 CultureInfo culture = current_culture;
461                                 if (current_culture_set && culture != null)
462                                         return culture;
463
464                                 if (default_culture != null)
465                                         return default_culture;
466
467                                 current_culture = culture = CultureInfo.ConstructCurrentCulture ();
468                                 return culture;
469                         }
470                         
471                         [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
472                         set {
473                                 if (value == null)
474                                         throw new ArgumentNullException ("value");
475
476                                 value.CheckNeutral ();
477                                 current_culture = value;
478                                 current_culture_set = true;
479                         }
480                 }
481
482                 public CultureInfo CurrentUICulture {
483                         get {
484                                 CultureInfo culture = current_ui_culture;
485                                 if (current_ui_culture_set && culture != null)
486                                         return culture;
487
488                                 if (default_ui_culture != null)
489                                         return default_ui_culture;
490
491                                 current_ui_culture = culture = CultureInfo.ConstructCurrentUICulture ();
492                                 return culture;
493                         }
494                         
495                         set {
496                                 if (value == null)
497                                         throw new ArgumentNullException ("value");
498                                 current_ui_culture = value;
499                                 current_ui_culture_set = true;
500                         }
501                 }
502
503                 public bool IsThreadPoolThread {
504                         get {
505                                 return IsThreadPoolThreadInternal;
506                         }
507                 }
508
509                 internal bool IsThreadPoolThreadInternal {
510                         get {
511                                 return Internal.threadpool_thread;
512                         }
513                         set {
514                                 Internal.threadpool_thread = value;
515                         }
516                 }
517
518                 public bool IsAlive {
519                         get {
520                                 ThreadState curstate = GetState (Internal);
521                                 
522                                 if((curstate & ThreadState.Aborted) != 0 ||
523                                    (curstate & ThreadState.Stopped) != 0 ||
524                                    (curstate & ThreadState.Unstarted) != 0) {
525                                         return(false);
526                                 } else {
527                                         return(true);
528                                 }
529                         }
530                 }
531
532                 public bool IsBackground {
533                         get {
534                                 ThreadState thread_state = GetState (Internal);
535                                 if ((thread_state & ThreadState.Stopped) != 0)
536                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
537
538                                 return (thread_state & ThreadState.Background) != 0;
539                         }
540                         
541                         set {
542                                 if (value) {
543                                         SetState (Internal, ThreadState.Background);
544                                 } else {
545                                         ClrState (Internal, ThreadState.Background);
546                                 }
547                         }
548                 }
549
550                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
551                 private extern static string GetName_internal (InternalThread thread);
552
553                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
554                 private extern static void SetName_internal (InternalThread thread, String name);
555
556                 /* 
557                  * The thread name must be shared by appdomains, so it is stored in
558                  * unmanaged code.
559                  */
560
561                 public string Name {
562                         get {
563                                 return GetName_internal (Internal);
564                         }
565                         
566                         set {
567                                 SetName_internal (Internal, value);
568                         }
569                 }
570
571                 public ThreadPriority Priority {
572                         get {
573                                 return (ThreadPriority)GetPriority (Internal);
574                         }
575                         
576                         set {
577                                 // FIXME: This doesn't do anything yet
578                                 SetPriority (Internal, (int)value);
579                         }
580                 }
581
582                 public ThreadState ThreadState {
583                         get {
584                                 return GetState (Internal);
585                         }
586                 }
587
588                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
589                 private extern static void Abort_internal (InternalThread thread, object stateInfo);
590
591                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
592                 private extern static int GetPriority (InternalThread thread);
593
594                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
595                 private extern static void SetPriority (InternalThread thread, int priority);
596
597                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
598                 public void Abort () 
599                 {
600                         Abort_internal (Internal, null);
601                 }
602
603                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
604                 public void Abort (object stateInfo) 
605                 {
606                         Abort_internal (Internal, stateInfo);
607                 }
608
609                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
610                 extern object GetAbortExceptionState ();
611
612                 internal object AbortReason {
613                         get {
614                                 return GetAbortExceptionState ();
615                         }
616                 }
617
618                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
619                 private extern static void Interrupt_internal (InternalThread thread);
620                 
621                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
622                 public void Interrupt ()
623                 {
624                         Interrupt_internal (Internal);
625                 }
626
627                 // The current thread joins with 'this'. Set ms to 0 to block
628                 // until this actually exits.
629                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
630                 private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
631                 
632                 public void Join()
633                 {
634                         Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
635                 }
636
637                 public bool Join(int millisecondsTimeout)
638                 {
639                         if (millisecondsTimeout < Timeout.Infinite)
640                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
641
642                         return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
643                 }
644
645                 public bool Join(TimeSpan timeout)
646                 {
647                         long ms = (long) timeout.TotalMilliseconds;
648                         if (ms < Timeout.Infinite || ms > Int32.MaxValue)
649                                 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
650
651                         return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
652                 }
653
654                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
655                 public extern static void MemoryBarrier ();
656
657                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
658                 private extern void Resume_internal();
659
660                 [Obsolete ("")]
661                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
662                 public void Resume () 
663                 {
664                         Resume_internal ();
665                 }
666
667                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
668                 private extern static void SpinWait_nop ();
669
670
671                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
672                 public static void SpinWait (int iterations) 
673                 {
674                         if (iterations < 0)
675                                 return;
676                         while (iterations-- > 0)
677                         {
678                                 SpinWait_nop ();
679                         }
680                 }
681
682                 private void StartInternal ()
683                 {
684                         current_thread = this;
685
686                         if (m_Delegate is ThreadStart) {
687                                 ((ThreadStart) m_Delegate) ();
688                         } else {
689                                 ((ParameterizedThreadStart) m_Delegate) (m_ThreadStartArg);
690                         }
691                 }
692
693                 public void Start() {
694                         // propagate informations from the original thread to the new thread
695                         ec_to_set = ExecutionContext.Capture (false, true);
696                         Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
697
698                         // Thread_internal creates and starts the new thread, 
699                         if (Thread_internal((ThreadStart) StartInternal) == (IntPtr) 0)
700                                 throw new SystemException ("Thread creation failed.");
701                 }
702
703                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
704                 private extern static void Suspend_internal(InternalThread thread);
705
706                 [Obsolete ("")]
707                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
708                 public void Suspend ()
709                 {
710                         Suspend_internal (Internal);
711                 }
712
713                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
714                 extern private static void SetState (InternalThread thread, ThreadState set);
715
716                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
717                 extern private static void ClrState (InternalThread thread, ThreadState clr);
718
719                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
720                 extern private static ThreadState GetState (InternalThread thread);
721
722                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
723                 extern public static byte VolatileRead (ref byte address);
724                 
725                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
726                 extern public static double VolatileRead (ref double address);
727                 
728                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
729                 extern public static short VolatileRead (ref short address);
730                 
731                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
732                 extern public static int VolatileRead (ref int address);
733                 
734                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
735                 extern public static long VolatileRead (ref long address);
736                 
737                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
738                 extern public static IntPtr VolatileRead (ref IntPtr address);
739                 
740                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
741                 extern public static object VolatileRead (ref object address);
742
743                 [CLSCompliant(false)]
744                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
745                 extern public static sbyte VolatileRead (ref sbyte address);
746                 
747                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
748                 extern public static float VolatileRead (ref float address);
749
750                 [CLSCompliant (false)]
751                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
752                 extern public static ushort VolatileRead (ref ushort address);
753
754                 [CLSCompliant (false)]
755                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
756                 extern public static uint VolatileRead (ref uint address);
757
758                 [CLSCompliant (false)]
759                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
760                 extern public static ulong VolatileRead (ref ulong address);
761
762                 [CLSCompliant (false)]
763                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
764                 extern public static UIntPtr VolatileRead (ref UIntPtr address);
765
766                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
767                 extern public static void VolatileWrite (ref byte address, byte value);
768                 
769                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
770                 extern public static void VolatileWrite (ref double address, double value);
771                 
772                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
773                 extern public static void VolatileWrite (ref short address, short value);
774                 
775                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
776                 extern public static void VolatileWrite (ref int address, int value);
777                 
778                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
779                 extern public static void VolatileWrite (ref long address, long value);
780                 
781                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
782                 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
783                 
784                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
785                 extern public static void VolatileWrite (ref object address, object value);
786
787                 [CLSCompliant(false)]
788                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
789                 extern public static void VolatileWrite (ref sbyte address, sbyte value);
790                 
791                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
792                 extern public static void VolatileWrite (ref float address, float value);
793
794                 [CLSCompliant (false)]
795                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
796                 extern public static void VolatileWrite (ref ushort address, ushort value);
797
798                 [CLSCompliant (false)]
799                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
800                 extern public static void VolatileWrite (ref uint address, uint value);
801
802                 [CLSCompliant (false)]
803                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
804                 extern public static void VolatileWrite (ref ulong address, ulong value);
805
806                 [CLSCompliant (false)]
807                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
808                 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
809                 
810                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
811                 extern static int SystemMaxStackStize ();
812
813                 static int GetProcessDefaultStackSize (int maxStackSize)
814                 {
815                         if (maxStackSize < 131072) // make sure stack is at least 128k big
816                                 return 131072;
817
818                         int page_size = Environment.GetPageSize ();
819
820                         if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
821                                 maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
822
823                         /* Respect the max stack size imposed by the system*/
824                         return Math.Min (maxStackSize, SystemMaxStackStize ());
825                 }
826
827                 void SetStart (MulticastDelegate start, int maxStackSize)
828                 {
829                         m_Delegate = start;
830                         Internal.stack_size = maxStackSize;
831                 }
832
833                 public ExecutionContext ExecutionContext {
834                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
835                         get {
836                                 if (_ec == null)
837                                         _ec = new ExecutionContext ();
838                                 return _ec;
839                         }
840                         internal set {
841                                 _ec = value;
842                         }
843                 }
844
845                 internal bool HasExecutionContext {
846                         get {
847                                 return _ec != null;
848                         }
849                 }
850
851                 internal void BranchExecutionContext (out ExecutionContext.Switcher switcher)
852                 {
853                         if (_ec == null) {
854                                 switcher =  new ExecutionContext.Switcher ();
855                         } else {
856                                 switcher = new ExecutionContext.Switcher (_ec);
857                                 _ec.CopyOnWrite = true;
858                         }
859                 }
860
861                 internal void RestoreExecutionContext (ref ExecutionContext.Switcher switcher)
862                 {
863                         if (switcher.IsEmpty) {
864                                 _ec = null;
865                                 return;
866                         }
867
868                         switcher.Restore (_ec);
869                 }
870
871                 public int ManagedThreadId {
872                         [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
873                         get {
874                                 return Internal.managed_id;
875                         }
876                 }
877
878                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
879                 public static void BeginCriticalRegion ()
880                 {
881                         CurrentThread.Internal.critical_region_level++;
882                 }
883
884                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
885                 public static void EndCriticalRegion ()
886                 {
887                         CurrentThread.Internal.critical_region_level--;
888                 }
889
890                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
891                 public static void BeginThreadAffinity ()
892                 {
893                         // Managed and native threads are currently bound together.
894                 }
895
896                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
897                 public static void EndThreadAffinity ()
898                 {
899                         // Managed and native threads are currently bound together.
900                 }
901
902                 public ApartmentState GetApartmentState ()
903                 {
904                         return (ApartmentState)Internal.apartment_state;
905                 }
906
907                 public void SetApartmentState (ApartmentState state)
908                 {
909                         if (!TrySetApartmentState (state))
910                                 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
911                 }
912
913                 public bool TrySetApartmentState (ApartmentState state) 
914                 {
915                         if ((ThreadState & ThreadState.Unstarted) == 0)
916                                 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
917
918                         if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown && 
919                             (ApartmentState)Internal.apartment_state != state)
920                                 return false;
921
922                         Internal.apartment_state = (byte)state;
923
924                         return true;
925                 }
926                 
927                 [ComVisible (false)]
928                 public override int GetHashCode ()
929                 {
930                         return ManagedThreadId;
931                 }
932
933                 public void Start (object parameter)
934                 {
935                         m_ThreadStartArg = parameter;
936                         Start ();
937                 }
938
939 #if !MOBILE
940                 void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
941                 {
942                         throw new NotImplementedException ();
943                 }
944
945                 void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
946                 {
947                         throw new NotImplementedException ();
948                 }
949
950                 void _Thread.GetTypeInfoCount (out uint pcTInfo)
951                 {
952                         throw new NotImplementedException ();
953                 }
954
955                 void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
956                         IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
957                 {
958                         throw new NotImplementedException ();
959                 }
960 #endif
961
962                 internal CultureInfo GetCurrentUICultureNoAppX ()
963                 {
964                         return CultureInfo.CurrentUICulture;
965                 }
966         }
967 }