Thread.cs 31 KB

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