Thread.cs 31 KB

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