Merge branch 'master' of github.com:mono/mono
[mono.git] / mcs / class / corlib / System.Threading / Thread.cs
1 //
2 // System.Threading.Thread.cs
3 //
4 // Author:
5 //   Dick Porter (dick@ximian.com)
6 //
7 // (C) Ximian, Inc.  http://www.ximian.com
8 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System.Runtime.Remoting.Contexts;
31 using System.Runtime.Serialization;
32 using System.Runtime.Serialization.Formatters.Binary;
33 using System.Security.Permissions;
34 using System.Security.Principal;
35 using System.Globalization;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.InteropServices;
38 using System.IO;
39 using System.Collections;
40 using System.Reflection;
41 using System.Security;
42 using System.Runtime.ConstrainedExecution;
43
44 namespace System.Threading {
45
46         internal 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                 private IntPtr unused0;
56                 internal bool threadpool_thread;
57                 /* accessed only from unmanaged code */
58                 private IntPtr name;
59                 private int name_len; 
60                 private ThreadState state;
61                 private object abort_exc;
62                 private int abort_state_handle;
63                 /* thread_id is only accessed from unmanaged code */
64                 internal Int64 thread_id;
65                 
66                 /* start_notify is used by the runtime to signal that Start()
67                  * is ok to return
68                  */
69                 private IntPtr start_notify;
70                 private IntPtr stack_ptr;
71                 private UIntPtr static_data; /* GC-tracked */
72                 private IntPtr jit_data;
73                 private IntPtr lock_data;
74                 /* current System.Runtime.Remoting.Contexts.Context instance
75                    keep as an object to avoid triggering its class constructor when not needed */
76                 private object current_appcontext;
77                 internal int stack_size;
78                 private IntPtr appdomain_refs;
79                 private int interruption_requested;
80                 private IntPtr suspend_event;
81                 private IntPtr suspended_event;
82                 private IntPtr resume_event;
83                 private IntPtr synch_cs;
84                 private bool thread_dump_requested;
85                 private IntPtr end_stack;
86                 private bool thread_interrupt_requested;
87                 internal byte apartment_state;
88                 internal volatile int critical_region_level;
89                 private int small_id;
90                 private IntPtr manage_callback;
91                 private object pending_exception;
92                 /* This is the ExecutionContext that will be set by
93                    start_wrapper() in the runtime. */
94                 private ExecutionContext ec_to_set;
95
96                 private IntPtr interrupt_on_stop;
97
98                 /* 
99                  * These fields are used to avoid having to increment corlib versions
100                  * when a new field is added to the unmanaged MonoThread structure.
101                  */
102                 private IntPtr unused3;
103                 private IntPtr unused4;
104                 private IntPtr unused5;
105                 private IntPtr unused6;
106                 #endregion
107 #pragma warning restore 169, 414, 649
108
109                 internal int managed_id;
110
111                 internal byte[] _serialized_principal;
112                 internal int _serialized_principal_version;
113
114                 internal byte[] serialized_culture_info;
115                 internal byte[] serialized_ui_culture_info;
116
117                 /* If the current_lcid() isn't known by CultureInfo,
118                  * it will throw an exception which may cause
119                  * String.Concat to try and recursively look up the
120                  * CurrentCulture, which will throw an exception, etc.
121                  * Use a boolean to short-circuit this scenario.
122                  */
123                 internal bool in_currentculture=false;
124
125                 // Closes the system thread handle
126                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
127                 private extern void Thread_free_internal(IntPtr handle);
128
129                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
130                 ~InternalThread() {
131                         Thread_free_internal(system_thread_handle);
132                 }
133         }
134
135         [ClassInterface (ClassInterfaceType.None)]
136         [ComVisible (true)]
137         [ComDefaultInterface (typeof (_Thread))]
138         public sealed class Thread : CriticalFinalizerObject, _Thread {
139 #pragma warning disable 414             
140                 #region Sync with metadata/object-internals.h
141                 private InternalThread internal_thread;
142                 object start_obj;
143                 private ExecutionContext ec_to_set;
144                 #endregion
145 #pragma warning restore 414
146
147                 IPrincipal principal;
148                 int principal_version;
149
150                 // the name of local_slots, current_thread and _ec is
151                 // important because they are used by the runtime.
152                 [ThreadStatic]
153                 static object[] local_slots;
154
155                 [ThreadStatic]
156                 static Thread current_thread;
157
158                 /* The actual ExecutionContext of the thread.  It's
159                    ThreadStatic so that it's not shared between
160                    AppDomains. */
161                 [ThreadStatic]
162                 static ExecutionContext _ec;
163
164                 // can be both a ThreadStart and a ParameterizedThreadStart
165                 private MulticastDelegate threadstart;
166                 //private string thread_name=null;
167
168                 private static int _managed_id_counter;
169
170                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
171                 private extern void ConstructInternalThread ();
172
173                 private InternalThread Internal {
174                         get {
175                                 if (internal_thread == null)
176                                         ConstructInternalThread ();
177                                 return internal_thread;
178                         }
179                 }
180
181                 public static Context CurrentContext {
182                         [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
183                         get {
184                                 return(AppDomain.InternalGetContext ());
185                         }
186                 }
187
188                 /*
189                  * These two methods return an array in the target
190                  * domain with the same content as the argument.  If
191                  * the argument is already in the target domain, then
192                  * the argument is returned, otherwise a copy.
193                  */
194                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
195                 private extern static byte[] ByteArrayToRootDomain (byte[] arr);
196
197                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
198                 private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
199
200 #if !MOONLIGHT
201                 public static IPrincipal CurrentPrincipal {
202                         get {
203                                 Thread th = CurrentThread;
204
205                                 if (th.principal_version != th.Internal._serialized_principal_version)
206                                         th.principal = null;
207
208                                 if (th.principal != null)
209                                         return th.principal;
210
211                                 if (th.Internal._serialized_principal != null) {
212                                         try {
213                                                 BinaryFormatter bf = new BinaryFormatter ();
214                                                 MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
215                                                 th.principal = (IPrincipal) bf.Deserialize (ms);
216                                                 th.principal_version = th.Internal._serialized_principal_version;
217                                                 return th.principal;
218                                         } catch (Exception) {
219                                         }
220                                 }
221
222                                 th.principal = GetDomain ().DefaultPrincipal;
223                                 th.principal_version = th.Internal._serialized_principal_version;
224                                 return th.principal;
225                         }
226                         [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
227                         set {
228                                 Thread th = CurrentThread;
229
230                                 ++th.Internal._serialized_principal_version;
231                                 try {
232                                         BinaryFormatter bf = new BinaryFormatter ();
233                                         MemoryStream ms = new MemoryStream ();
234                                         bf.Serialize (ms, value);
235                                         th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
236                                 } catch (Exception) {
237                                         th.Internal._serialized_principal = null;
238                                 }
239
240                                 th.principal = value;
241                                 th.principal_version = th.Internal._serialized_principal_version;
242                         }
243                 }
244 #endif
245
246                 // Looks up the object associated with the current thread
247                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
248                 private extern static InternalThread CurrentInternalThread_internal();
249
250                 public static Thread CurrentThread {
251                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
252                         get {
253                                 if (current_thread == null)
254                                         current_thread = new Thread (CurrentInternalThread_internal ());
255                                 return current_thread;
256                         }
257                 }
258
259                 internal static int CurrentThreadId {
260                         get {
261                                 return (int)(CurrentThread.internal_thread.thread_id);
262                         }
263                 }
264
265 #if !MOONLIGHT
266                 // Stores a hash keyed by strings of LocalDataStoreSlot objects
267                 static Hashtable datastorehash;
268                 private static object datastore_lock = new object ();
269                 
270                 private static void InitDataStoreHash () {
271                         lock (datastore_lock) {
272                                 if (datastorehash == null) {
273                                         datastorehash = Hashtable.Synchronized(new Hashtable());
274                                 }
275                         }
276                 }
277                 
278                 public static LocalDataStoreSlot AllocateNamedDataSlot (string name) {
279                         lock (datastore_lock) {
280                                 if (datastorehash == null)
281                                         InitDataStoreHash ();
282                                 LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
283                                 if (slot != null) {
284                                         // This exception isnt documented (of
285                                         // course) but .net throws it
286                                         throw new ArgumentException("Named data slot already added");
287                                 }
288                         
289                                 slot = AllocateDataSlot ();
290
291                                 datastorehash.Add (name, slot);
292
293                                 return slot;
294                         }
295                 }
296
297                 public static void FreeNamedDataSlot (string name) {
298                         lock (datastore_lock) {
299                                 if (datastorehash == null)
300                                         InitDataStoreHash ();
301                                 LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
302
303                                 if (slot != null) {
304                                         datastorehash.Remove (slot);
305                                 }
306                         }
307                 }
308
309                 public static LocalDataStoreSlot AllocateDataSlot () {
310                         return new LocalDataStoreSlot (true);
311                 }
312
313                 public static object GetData (LocalDataStoreSlot slot) {
314                         object[] slots = local_slots;
315                         if (slot == null)
316                                 throw new ArgumentNullException ("slot");
317                         if (slots != null && slot.slot < slots.Length)
318                                 return slots [slot.slot];
319                         return null;
320                 }
321
322                 public static void SetData (LocalDataStoreSlot slot, object data) {
323                         object[] slots = local_slots;
324                         if (slot == null)
325                                 throw new ArgumentNullException ("slot");
326                         if (slots == null) {
327                                 slots = new object [slot.slot + 2];
328                                 local_slots = slots;
329                         } else if (slot.slot >= slots.Length) {
330                                 object[] nslots = new object [slot.slot + 2];
331                                 slots.CopyTo (nslots, 0);
332                                 slots = nslots;
333                                 local_slots = slots;
334                         }
335                         slots [slot.slot] = data;
336                 }
337
338                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
339                 internal extern static void FreeLocalSlotValues (int slot, bool thread_local);
340
341                 public static LocalDataStoreSlot GetNamedDataSlot(string name) {
342                         lock (datastore_lock) {
343                                 if (datastorehash == null)
344                                         InitDataStoreHash ();
345                                 LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
346
347                                 if(slot==null) {
348                                         slot=AllocateNamedDataSlot(name);
349                                 }
350                         
351                                 return(slot);
352                         }
353                 }
354 #endif
355                 
356                 public static AppDomain GetDomain() {
357                         return AppDomain.CurrentDomain;
358                 }
359
360                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
361                 public extern static int GetDomainID();
362
363                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
364                 private extern static void ResetAbort_internal();
365
366                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
367                 public static void ResetAbort ()
368                 {
369                         ResetAbort_internal ();
370                 }
371
372 #if NET_4_0 || BOOTSTRAP_NET_4_0
373                 [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
374                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
375                 public extern static bool Yield ();
376 #endif
377
378
379                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
380                 private extern static void Sleep_internal(int ms);
381
382                 public static void Sleep (int millisecondsTimeout)
383                 {
384                         if (millisecondsTimeout < Timeout.Infinite)
385                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
386
387                         Sleep_internal (millisecondsTimeout);
388                 }
389
390                 public static void Sleep (TimeSpan timeout)
391                 {
392                         long ms = (long) timeout.TotalMilliseconds;
393                         if (ms < Timeout.Infinite || ms > Int32.MaxValue)
394                                 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
395
396                         Sleep_internal ((int) ms);
397                 }
398
399                 // Returns the system thread handle
400                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
401                 private extern IntPtr Thread_internal (MulticastDelegate start);
402
403                 public Thread(ThreadStart start) {
404                         if(start==null) {
405                                 throw new ArgumentNullException("Null ThreadStart");
406                         }
407                         threadstart=start;
408                 }
409
410                 private Thread (InternalThread it) {
411                         internal_thread = it;
412                 }
413
414 #if !MOONLIGHT
415                 [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
416                 public ApartmentState ApartmentState {
417                         get {
418                                 if ((ThreadState & ThreadState.Stopped) != 0)
419                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
420
421                                 return (ApartmentState)Internal.apartment_state;
422                         }
423
424                         set {
425                                 TrySetApartmentState (value);
426                         }
427                 }
428 #endif // !NET_2_1
429
430                 //[MethodImplAttribute (MethodImplOptions.InternalCall)]
431                 //private static extern int current_lcid ();
432
433                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
434                 private extern static CultureInfo GetCachedCurrentCulture (InternalThread thread);
435
436                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
437                 private extern void SetCachedCurrentCulture (CultureInfo culture);
438
439                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
440                 private extern static CultureInfo GetCachedCurrentUICulture (InternalThread thread);
441
442                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
443                 private extern void SetCachedCurrentUICulture (CultureInfo culture);
444
445                 /* FIXME: in_currentculture exists once, but
446                    culture_lock is once per appdomain.  Is it correct
447                    to lock this way? */
448                 static object culture_lock = new object ();
449                 
450                 /*
451                  * Thread objects are shared between appdomains, and CurrentCulture
452                  * should always return an object in the calling appdomain. See bug
453                  * http://bugzilla.ximian.com/show_bug.cgi?id=50049 for more info.
454                  * This is hard to implement correctly and efficiently, so the current
455                  * implementation is not perfect: changes made in one appdomain to the 
456                  * state of the current cultureinfo object are not visible to other 
457                  * appdomains.
458                  */             
459                 public CultureInfo CurrentCulture {
460                         get {
461                                 if (Internal.in_currentculture)
462                                         /* Bail out */
463                                         return CultureInfo.InvariantCulture;
464
465                                 CultureInfo culture = GetCachedCurrentCulture (Internal);
466                                 if (culture != null)
467                                         return culture;
468
469                                 byte[] arr = ByteArrayToCurrentDomain (Internal.serialized_culture_info);
470                                 if (arr == null) {
471                                         lock (culture_lock) {
472                                                 Internal.in_currentculture=true;
473                                                 culture = CultureInfo.ConstructCurrentCulture ();
474                                                 //
475                                                 // Don't serialize the culture in this case to avoid
476                                                 // initializing the serialization infrastructure in the
477                                                 // common case when the culture is not set explicitly.
478                                                 //
479                                                 SetCachedCurrentCulture (culture);
480                                                 Internal.in_currentculture = false;
481                                                 NumberFormatter.SetThreadCurrentCulture (culture);
482                                                 return culture;
483                                         }
484                                 }
485
486                                 /*
487                                  * No cultureinfo object exists for this domain, so create one
488                                  * by deserializing the serialized form.
489                                  */
490                                 Internal.in_currentculture = true;
491                                 try {
492                                         BinaryFormatter bf = new BinaryFormatter ();
493                                         MemoryStream ms = new MemoryStream (arr);
494                                         culture = (CultureInfo)bf.Deserialize (ms);
495                                         SetCachedCurrentCulture (culture);
496                                 } finally {
497                                         Internal.in_currentculture = false;
498                                 }
499
500                                 NumberFormatter.SetThreadCurrentCulture (culture);
501                                 return culture;
502                         }
503                         
504                         [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
505                         set {
506                                 if (value == null)
507                                         throw new ArgumentNullException ("value");
508
509                                 CultureInfo culture = GetCachedCurrentCulture (Internal);
510                                 if (culture == value)
511                                         return;
512
513                                 value.CheckNeutral ();
514                                 Internal.in_currentculture = true;
515                                 try {
516                                         SetCachedCurrentCulture (value);
517
518                                         byte[] serialized_form = null;
519
520                                         if (value.IsReadOnly && value.cached_serialized_form != null) {
521                                                 serialized_form = value.cached_serialized_form;
522                                         } else {
523                                                 BinaryFormatter bf = new BinaryFormatter();
524                                                 MemoryStream ms = new MemoryStream ();
525                                                 bf.Serialize (ms, value);
526
527                                                 serialized_form = ms.GetBuffer ();
528                                                 if (value.IsReadOnly)
529                                                         value.cached_serialized_form = serialized_form;
530                                         }
531
532                                         Internal.serialized_culture_info = ByteArrayToRootDomain (serialized_form);
533                                 } finally {
534                                         Internal.in_currentculture = false;
535                                 }
536                                 NumberFormatter.SetThreadCurrentCulture (value);
537                         }
538                 }
539
540                 public CultureInfo CurrentUICulture {
541                         get {
542                                 if (Internal.in_currentculture)
543                                         /* Bail out */
544                                         return CultureInfo.InvariantCulture;
545
546                                 CultureInfo culture = GetCachedCurrentUICulture (Internal);
547                                 if (culture != null)
548                                         return culture;
549
550                                 byte[] arr = ByteArrayToCurrentDomain (Internal.serialized_ui_culture_info);
551                                 if (arr == null) {
552                                         lock (culture_lock) {
553                                                 Internal.in_currentculture=true;
554                                                 /* We don't
555                                                  * distinguish
556                                                  * between
557                                                  * System and
558                                                  * UI cultures
559                                                  */
560                                                 culture = CultureInfo.ConstructCurrentUICulture ();
561                                                 //
562                                                 // Don't serialize the culture in this case to avoid
563                                                 // initializing the serialization infrastructure in the
564                                                 // common case when the culture is not set explicitly.
565                                                 //
566                                                 SetCachedCurrentUICulture (culture);
567                                                 Internal.in_currentculture = false;
568                                                 return culture;
569                                         }
570                                 }
571
572                                 /*
573                                  * No cultureinfo object exists for this domain, so create one
574                                  * by deserializing the serialized form.
575                                  */
576                                 Internal.in_currentculture = true;
577                                 try {
578                                         BinaryFormatter bf = new BinaryFormatter ();
579                                         MemoryStream ms = new MemoryStream (arr);
580                                         culture = (CultureInfo)bf.Deserialize (ms);
581                                         SetCachedCurrentUICulture (culture);
582                                 }
583                                 finally {
584                                         Internal.in_currentculture = false;
585                                 }
586
587                                 return culture;
588                         }
589                         
590                         set {
591                                 if (value == null)
592                                         throw new ArgumentNullException ("value");
593
594                                 CultureInfo culture = GetCachedCurrentUICulture (Internal);
595                                 if (culture == value)
596                                         return;
597
598                                 Internal.in_currentculture = true;
599                                 try {
600                                         SetCachedCurrentUICulture (value);
601
602                                         byte[] serialized_form = null;
603
604                                         if (value.IsReadOnly && value.cached_serialized_form != null) {
605                                                 serialized_form = value.cached_serialized_form;
606                                         } else {
607                                                 BinaryFormatter bf = new BinaryFormatter();
608                                                 MemoryStream ms = new MemoryStream ();
609                                                 bf.Serialize (ms, value);
610
611                                                 serialized_form = ms.GetBuffer ();
612                                                 if (value.IsReadOnly)
613                                                         value.cached_serialized_form = serialized_form;
614                                         }
615
616                                         Internal.serialized_ui_culture_info = ByteArrayToRootDomain (serialized_form);
617                                 } finally {
618                                         Internal.in_currentculture = false;
619                                 }
620                         }
621                 }
622
623                 public bool IsThreadPoolThread {
624                         get {
625                                 return IsThreadPoolThreadInternal;
626                         }
627                 }
628
629                 internal bool IsThreadPoolThreadInternal {
630                         get {
631                                 return Internal.threadpool_thread;
632                         }
633                         set {
634                                 Internal.threadpool_thread = value;
635                         }
636                 }
637
638                 public bool IsAlive {
639                         get {
640                                 ThreadState curstate = GetState (Internal);
641                                 
642                                 if((curstate & ThreadState.Aborted) != 0 ||
643                                    (curstate & ThreadState.Stopped) != 0 ||
644                                    (curstate & ThreadState.Unstarted) != 0) {
645                                         return(false);
646                                 } else {
647                                         return(true);
648                                 }
649                         }
650                 }
651
652                 public bool IsBackground {
653                         get {
654                                 ThreadState thread_state = GetState (Internal);
655                                 if ((thread_state & ThreadState.Stopped) != 0)
656                                         throw new ThreadStateException ("Thread is dead; state can not be accessed.");
657
658                                 return (thread_state & ThreadState.Background) != 0;
659                         }
660                         
661                         set {
662                                 if (value) {
663                                         SetState (Internal, ThreadState.Background);
664                                 } else {
665                                         ClrState (Internal, ThreadState.Background);
666                                 }
667                         }
668                 }
669
670                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
671                 private extern static string GetName_internal (InternalThread thread);
672
673                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
674                 private extern static void SetName_internal (InternalThread thread, String name);
675
676                 /* 
677                  * The thread name must be shared by appdomains, so it is stored in
678                  * unmanaged code.
679                  */
680
681                 public string Name {
682                         get {
683                                 return GetName_internal (Internal);
684                         }
685                         
686                         set {
687                                 SetName_internal (Internal, value);
688                         }
689                 }
690
691 #if !MOONLIGHT
692                 public ThreadPriority Priority {
693                         get {
694                                 return(ThreadPriority.Lowest);
695                         }
696                         
697                         set {
698                                 // FIXME: Implement setter.
699                         }
700                 }
701 #endif
702
703                 public ThreadState ThreadState {
704                         get {
705                                 return GetState (Internal);
706                         }
707                 }
708
709                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
710                 private extern static void Abort_internal (InternalThread thread, object stateInfo);
711
712                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
713                 public void Abort () 
714                 {
715                         Abort_internal (Internal, null);
716                 }
717
718 #if !MOONLIGHT
719                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
720                 public void Abort (object stateInfo) 
721                 {
722                         Abort_internal (Internal, stateInfo);
723                 }
724
725                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
726                 internal extern object GetAbortExceptionState ();
727
728                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
729                 private extern static void Interrupt_internal (InternalThread thread);
730                 
731                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
732                 public void Interrupt ()
733                 {
734                         Interrupt_internal (Internal);
735                 }
736 #endif
737
738                 // The current thread joins with 'this'. Set ms to 0 to block
739                 // until this actually exits.
740                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
741                 private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
742                 
743                 public void Join()
744                 {
745                         Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
746                 }
747
748                 public bool Join(int millisecondsTimeout)
749                 {
750                         if (millisecondsTimeout < Timeout.Infinite)
751                                 throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
752
753                         return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
754                 }
755
756 #if !MOONLIGHT
757                 public bool Join(TimeSpan timeout)
758                 {
759                         long ms = (long) timeout.TotalMilliseconds;
760                         if (ms < Timeout.Infinite || ms > Int32.MaxValue)
761                                 throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
762
763                         return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
764                 }
765 #endif
766
767 #if NET_1_1
768                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
769                 public extern static void MemoryBarrier ();
770 #endif
771
772 #if !MOONLIGHT
773                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
774                 private extern void Resume_internal();
775
776                 [Obsolete ("")]
777                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
778                 public void Resume () 
779                 {
780                         Resume_internal ();
781                 }
782 #endif // !NET_2_1
783
784                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
785                 private extern static void SpinWait_nop ();
786
787
788                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
789                 public static void SpinWait (int iterations) 
790                 {
791                         if (iterations < 0)
792                                 return;
793                         while (iterations-- > 0)
794                         {
795                                 SpinWait_nop ();
796                         }
797                 }
798
799 #if MOONLIGHT
800                 private void StartSafe ()
801                 {
802                         current_thread = this;
803
804                         try {
805                                 if (threadstart is ThreadStart) {
806                                         ((ThreadStart) threadstart) ();
807                                 } else {
808                                         ((ParameterizedThreadStart) threadstart) (start_obj);
809                                 }
810                         } catch (ThreadAbortException) {
811                                 // do nothing
812                         } catch (Exception ex) {
813                                 MoonlightUnhandledException (ex);
814                         }
815                 }
816
817                 static MethodInfo moonlight_unhandled_exception = null;
818
819                 static internal void MoonlightUnhandledException (Exception e)
820                 {
821                         try {
822                                 if (moonlight_unhandled_exception == null) {
823                                         var assembly = System.Reflection.Assembly.Load ("System.Windows, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e");
824                                         var application = assembly.GetType ("System.Windows.Application");
825                                         moonlight_unhandled_exception = application.GetMethod ("OnUnhandledException", 
826                                                 System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
827                                 }
828                                 moonlight_unhandled_exception.Invoke (null, new object [] { null, e });
829                         }
830                         catch {
831                                 try {
832                                         Console.WriteLine ("Unexpected exception while trying to report unhandled application exception: {0}", e);
833                                 } catch {
834                                 }
835                         }
836                 }
837 #endif
838
839                 private void StartUnsafe ()
840                 {
841                         current_thread = this;
842
843                         if (threadstart is ThreadStart) {
844                                 ((ThreadStart) threadstart) ();
845                         } else {
846                                 ((ParameterizedThreadStart) threadstart) (start_obj);
847                         }
848                 }
849
850                 public void Start() {
851                         // propagate informations from the original thread to the new thread
852                         if (!ExecutionContext.IsFlowSuppressed ())
853                                 ec_to_set = ExecutionContext.Capture ();
854                         Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
855
856                         // Thread_internal creates and starts the new thread, 
857 #if MOONLIGHT
858                         if (Thread_internal((ThreadStart) StartSafe) == (IntPtr) 0)
859 #else
860                         if (Thread_internal((ThreadStart) StartUnsafe) == (IntPtr) 0)
861 #endif
862                                 throw new SystemException ("Thread creation failed.");
863                 }
864
865 #if !MOONLIGHT
866                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
867                 private extern static void Suspend_internal(InternalThread thread);
868
869                 [Obsolete ("")]
870                 [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
871                 public void Suspend ()
872                 {
873                         Suspend_internal (Internal);
874                 }
875 #endif // !NET_2_1
876
877                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
878                 extern private static void SetState (InternalThread thread, ThreadState set);
879
880                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
881                 extern private static void ClrState (InternalThread thread, ThreadState clr);
882
883                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
884                 extern private static ThreadState GetState (InternalThread thread);
885
886 #if NET_1_1
887                 
888                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
889                 extern public static byte VolatileRead (ref byte address);
890                 
891                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
892                 extern public static double VolatileRead (ref double address);
893                 
894                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
895                 extern public static short VolatileRead (ref short address);
896                 
897                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
898                 extern public static int VolatileRead (ref int address);
899                 
900                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
901                 extern public static long VolatileRead (ref long address);
902                 
903                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
904                 extern public static IntPtr VolatileRead (ref IntPtr address);
905                 
906                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
907                 extern public static object VolatileRead (ref object address);
908
909                 [CLSCompliant(false)]
910                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
911                 extern public static sbyte VolatileRead (ref sbyte address);
912                 
913                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
914                 extern public static float VolatileRead (ref float address);
915
916                 [CLSCompliant (false)]
917                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
918                 extern public static ushort VolatileRead (ref ushort address);
919
920                 [CLSCompliant (false)]
921                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
922                 extern public static uint VolatileRead (ref uint address);
923
924                 [CLSCompliant (false)]
925                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
926                 extern public static ulong VolatileRead (ref ulong address);
927
928                 [CLSCompliant (false)]
929                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
930                 extern public static UIntPtr VolatileRead (ref UIntPtr address);
931
932                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
933                 extern public static void VolatileWrite (ref byte address, byte value);
934                 
935                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
936                 extern public static void VolatileWrite (ref double address, double value);
937                 
938                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
939                 extern public static void VolatileWrite (ref short address, short value);
940                 
941                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
942                 extern public static void VolatileWrite (ref int address, int value);
943                 
944                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
945                 extern public static void VolatileWrite (ref long address, long value);
946                 
947                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
948                 extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
949                 
950                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
951                 extern public static void VolatileWrite (ref object address, object value);
952
953                 [CLSCompliant(false)]
954                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
955                 extern public static void VolatileWrite (ref sbyte address, sbyte value);
956                 
957                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
958                 extern public static void VolatileWrite (ref float address, float value);
959
960                 [CLSCompliant (false)]
961                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
962                 extern public static void VolatileWrite (ref ushort address, ushort value);
963
964                 [CLSCompliant (false)]
965                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
966                 extern public static void VolatileWrite (ref uint address, uint value);
967
968                 [CLSCompliant (false)]
969                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
970                 extern public static void VolatileWrite (ref ulong address, ulong value);
971
972                 [CLSCompliant (false)]
973                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
974                 extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
975                 
976 #endif
977
978                 private static int GetNewManagedId() {
979                         return Interlocked.Increment(ref _managed_id_counter);
980                 }
981
982                 public Thread (ThreadStart start, int maxStackSize)
983                 {
984                         if (start == null)
985                                 throw new ArgumentNullException ("start");
986                         if (maxStackSize < 131072)
987                                 throw new ArgumentException ("< 128 kb", "maxStackSize");
988
989                         threadstart = start;
990                         Internal.stack_size = maxStackSize;
991                 }
992
993                 public Thread (ParameterizedThreadStart start)
994                 {
995                         if (start == null)
996                                 throw new ArgumentNullException ("start");
997
998                         threadstart = start;
999                 }
1000
1001                 public Thread (ParameterizedThreadStart start, int maxStackSize)
1002                 {
1003                         if (start == null)
1004                                 throw new ArgumentNullException ("start");
1005                         if (maxStackSize < 131072)
1006                                 throw new ArgumentException ("< 128 kb", "maxStackSize");
1007
1008                         threadstart = start;
1009                         Internal.stack_size = maxStackSize;
1010                 }
1011
1012                 [MonoTODO ("limited to CompressedStack support")]
1013                 public ExecutionContext ExecutionContext {
1014                         [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
1015                         get {
1016                                 if (_ec == null)
1017                                         _ec = new ExecutionContext ();
1018                                 return _ec;
1019                         }
1020                 }
1021
1022                 public int ManagedThreadId {
1023                         [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
1024                         get {
1025                                 // Fastpath
1026                                 if (internal_thread != null && internal_thread.managed_id != 0)
1027                                         return internal_thread.managed_id;
1028
1029                                 if (Internal.managed_id == 0) {
1030                                         int new_managed_id = GetNewManagedId ();
1031                                         
1032                                         Interlocked.CompareExchange (ref Internal.managed_id, new_managed_id, 0);
1033                                 }
1034                                 
1035                                 return Internal.managed_id;
1036                         }
1037                 }
1038
1039                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
1040                 public static void BeginCriticalRegion ()
1041                 {
1042                         CurrentThread.Internal.critical_region_level++;
1043                 }
1044
1045                 [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
1046                 public static void EndCriticalRegion ()
1047                 {
1048                         CurrentThread.Internal.critical_region_level--;
1049                 }
1050
1051                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1052                 public static void BeginThreadAffinity ()
1053                 {
1054                         // Managed and native threads are currently bound together.
1055                 }
1056
1057                 [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
1058                 public static void EndThreadAffinity ()
1059                 {
1060                         // Managed and native threads are currently bound together.
1061                 }
1062
1063 #if !MOONLIGHT
1064                 public ApartmentState GetApartmentState ()
1065                 {
1066                         return (ApartmentState)Internal.apartment_state;
1067                 }
1068
1069                 public void SetApartmentState (ApartmentState state)
1070                 {
1071                         if (!TrySetApartmentState (state))
1072                                 throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
1073                 }
1074
1075                 public bool TrySetApartmentState (ApartmentState state) 
1076                 {
1077                         /* Only throw this exception when changing the
1078                          * state of another thread.  See bug 324338
1079                          */
1080                         if ((this != CurrentThread) &&
1081                             (ThreadState & ThreadState.Unstarted) == 0)
1082                                 throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
1083
1084                         if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown)
1085                                 return false;
1086
1087                         Internal.apartment_state = (byte)state;
1088
1089                         return true;
1090                 }
1091 #endif // !NET_2_1
1092                 
1093                 [ComVisible (false)]
1094                 public override int GetHashCode ()
1095                 {
1096                         return ManagedThreadId;
1097                 }
1098
1099                 public void Start (object parameter)
1100                 {
1101                         start_obj = parameter;
1102                         Start ();
1103                 }
1104
1105 #if !MOONLIGHT
1106                 // NOTE: This method doesn't show in the class library status page because
1107                 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
1108                 // But it's there!
1109                 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
1110                 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
1111                 [Obsolete ("see CompressedStack class")]
1112 #if NET_1_1
1113                 public
1114 #else
1115                 internal
1116 #endif
1117                 CompressedStack GetCompressedStack ()
1118                 {
1119                         // Note: returns null if no CompressedStack has been set.
1120                         // However CompressedStack.GetCompressedStack returns an 
1121                         // (empty?) CompressedStack instance.
1122                         CompressedStack cs = ExecutionContext.SecurityContext.CompressedStack;
1123                         return ((cs == null) || cs.IsEmpty ()) ? null : cs.CreateCopy ();
1124                 }
1125
1126                 // NOTE: This method doesn't show in the class library status page because
1127                 // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
1128                 // But it's there!
1129                 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
1130                 [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
1131                 [Obsolete ("see CompressedStack class")]
1132 #if NET_1_1
1133                 public
1134 #else
1135                 internal
1136 #endif
1137                 void SetCompressedStack (CompressedStack stack)
1138                 {
1139                         ExecutionContext.SecurityContext.CompressedStack = stack;
1140                 }
1141
1142 #endif
1143
1144 #if NET_1_1
1145                 void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
1146                 {
1147                         throw new NotImplementedException ();
1148                 }
1149
1150                 void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
1151                 {
1152                         throw new NotImplementedException ();
1153                 }
1154
1155                 void _Thread.GetTypeInfoCount (out uint pcTInfo)
1156                 {
1157                         throw new NotImplementedException ();
1158                 }
1159
1160                 void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
1161                         IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
1162                 {
1163                         throw new NotImplementedException ();
1164                 }
1165 #endif
1166         }
1167 }