Thread.cs 29 KB

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