Thread.cs 30 KB

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