Thread.cs 31 KB

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