Thread.cs 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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_lock in managed code, since it can result in deadlocks */
  85. private object synch_lock = new Object();
  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. private static int GetNewManagedId() {
  258. return Interlocked.Increment(ref _managed_id_counter);
  259. }
  260. public Thread(ThreadStart start) {
  261. if(start==null) {
  262. throw new ArgumentNullException("Null ThreadStart");
  263. }
  264. threadstart=start;
  265. managed_id=GetNewManagedId();
  266. }
  267. #if NET_2_0
  268. [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
  269. #endif
  270. public ApartmentState ApartmentState {
  271. get {
  272. if ((ThreadState & ThreadState.Stopped) != 0)
  273. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  274. return (ApartmentState)apartment_state;
  275. }
  276. set {
  277. #if NET_2_0
  278. TrySetApartmentState (value);
  279. #else
  280. if ((ThreadState & ThreadState.Unstarted) == 0)
  281. throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
  282. if (value != ApartmentState.STA && value != ApartmentState.MTA)
  283. throw new ArgumentException ("value is not a valid apartment state.");
  284. if ((ApartmentState)apartment_state == ApartmentState.Unknown)
  285. apartment_state = (byte)value;
  286. #endif
  287. }
  288. }
  289. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  290. private static extern int current_lcid ();
  291. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  292. private extern CultureInfo GetCachedCurrentCulture ();
  293. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  294. private extern byte[] GetSerializedCurrentCulture ();
  295. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  296. private extern void SetCachedCurrentCulture (CultureInfo culture);
  297. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  298. private extern void SetSerializedCurrentCulture (byte[] culture);
  299. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  300. private extern CultureInfo GetCachedCurrentUICulture ();
  301. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  302. private extern byte[] GetSerializedCurrentUICulture ();
  303. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  304. private extern void SetCachedCurrentUICulture (CultureInfo culture);
  305. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  306. private extern void SetSerializedCurrentUICulture (byte[] culture);
  307. /* If the current_lcid() isn't known by CultureInfo,
  308. * it will throw an exception which may cause
  309. * String.Concat to try and recursively look up the
  310. * CurrentCulture, which will throw an exception, etc.
  311. * Use a boolean to short-circuit this scenario.
  312. */
  313. private static bool in_currentculture=false;
  314. static object culture_lock = new object ();
  315. /*
  316. * Thread objects are shared between appdomains, and CurrentCulture
  317. * should always return an object in the calling appdomain. See bug
  318. * http://bugzilla.ximian.com/show_bug.cgi?id=50049 for more info.
  319. * This is hard to implement correctly and efficiently, so the current
  320. * implementation is not perfect: changes made in one appdomain to the
  321. * state of the current cultureinfo object are not visible to other
  322. * appdomains.
  323. */
  324. public CultureInfo CurrentCulture {
  325. get {
  326. if (in_currentculture)
  327. /* Bail out */
  328. return CultureInfo.InvariantCulture;
  329. CultureInfo culture = GetCachedCurrentCulture ();
  330. if (culture != null)
  331. return culture;
  332. byte[] arr = GetSerializedCurrentCulture ();
  333. if (arr == null) {
  334. lock (culture_lock) {
  335. in_currentculture=true;
  336. culture = CultureInfo.ConstructCurrentCulture ();
  337. //
  338. // Don't serialize the culture in this case to avoid
  339. // initializing the serialization infrastructure in the
  340. // common case when the culture is not set explicitly.
  341. //
  342. SetCachedCurrentCulture (culture);
  343. in_currentculture = false;
  344. return culture;
  345. }
  346. }
  347. /*
  348. * No cultureinfo object exists for this domain, so create one
  349. * by deserializing the serialized form.
  350. */
  351. in_currentculture = true;
  352. try {
  353. BinaryFormatter bf = new BinaryFormatter ();
  354. MemoryStream ms = new MemoryStream (arr);
  355. culture = (CultureInfo)bf.Deserialize (ms);
  356. SetCachedCurrentCulture (culture);
  357. } finally {
  358. in_currentculture = false;
  359. }
  360. return culture;
  361. }
  362. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  363. set {
  364. if (value == null)
  365. throw new ArgumentNullException ("value");
  366. value.CheckNeutral ();
  367. in_currentculture = true;
  368. try {
  369. BinaryFormatter bf = new BinaryFormatter();
  370. MemoryStream ms = new MemoryStream ();
  371. bf.Serialize (ms, value);
  372. SetCachedCurrentCulture (value);
  373. SetSerializedCurrentCulture (ms.GetBuffer ());
  374. } finally {
  375. in_currentculture = false;
  376. }
  377. }
  378. }
  379. public CultureInfo CurrentUICulture {
  380. get {
  381. if (in_currentculture)
  382. /* Bail out */
  383. return CultureInfo.InvariantCulture;
  384. CultureInfo culture = GetCachedCurrentUICulture ();
  385. if (culture != null)
  386. return culture;
  387. byte[] arr = GetSerializedCurrentUICulture ();
  388. if (arr == null) {
  389. lock (culture_lock) {
  390. in_currentculture=true;
  391. /* We don't
  392. * distinguish
  393. * between
  394. * System and
  395. * UI cultures
  396. */
  397. culture = CultureInfo.ConstructCurrentUICulture ();
  398. //
  399. // Don't serialize the culture in this case to avoid
  400. // initializing the serialization infrastructure in the
  401. // common case when the culture is not set explicitly.
  402. //
  403. SetCachedCurrentUICulture (culture);
  404. in_currentculture = false;
  405. return culture;
  406. }
  407. }
  408. /*
  409. * No cultureinfo object exists for this domain, so create one
  410. * by deserializing the serialized form.
  411. */
  412. in_currentculture = true;
  413. try {
  414. BinaryFormatter bf = new BinaryFormatter ();
  415. MemoryStream ms = new MemoryStream (arr);
  416. culture = (CultureInfo)bf.Deserialize (ms);
  417. SetCachedCurrentUICulture (culture);
  418. }
  419. finally {
  420. in_currentculture = false;
  421. }
  422. return culture;
  423. }
  424. set {
  425. in_currentculture = true;
  426. if (value == null)
  427. throw new ArgumentNullException ("value");
  428. try {
  429. BinaryFormatter bf = new BinaryFormatter();
  430. MemoryStream ms = new MemoryStream ();
  431. bf.Serialize (ms, value);
  432. SetCachedCurrentUICulture (value);
  433. SetSerializedCurrentUICulture (ms.GetBuffer ());
  434. } finally {
  435. in_currentculture = false;
  436. }
  437. }
  438. }
  439. public bool IsThreadPoolThread {
  440. get {
  441. return IsThreadPoolThreadInternal;
  442. }
  443. }
  444. internal bool IsThreadPoolThreadInternal {
  445. get {
  446. return threadpool_thread;
  447. }
  448. set {
  449. threadpool_thread = value;
  450. }
  451. }
  452. public bool IsAlive {
  453. get {
  454. ThreadState curstate = GetState ();
  455. if((curstate & ThreadState.Aborted) != 0 ||
  456. (curstate & ThreadState.Stopped) != 0 ||
  457. (curstate & ThreadState.Unstarted) != 0) {
  458. return(false);
  459. } else {
  460. return(true);
  461. }
  462. }
  463. }
  464. public bool IsBackground {
  465. get {
  466. ThreadState thread_state = GetState ();
  467. if ((thread_state & ThreadState.Stopped) != 0)
  468. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  469. return (thread_state & ThreadState.Background) != 0;
  470. }
  471. set {
  472. if (value) {
  473. SetState (ThreadState.Background);
  474. } else {
  475. ClrState (ThreadState.Background);
  476. }
  477. }
  478. }
  479. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  480. private extern string GetName_internal ();
  481. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  482. private extern void SetName_internal (String name);
  483. /*
  484. * The thread name must be shared by appdomains, so it is stored in
  485. * unmanaged code.
  486. */
  487. public string Name {
  488. get {
  489. return GetName_internal ();
  490. }
  491. set {
  492. SetName_internal (value);
  493. }
  494. }
  495. public ThreadPriority Priority {
  496. get {
  497. return(ThreadPriority.Lowest);
  498. }
  499. set {
  500. // FIXME: Implement setter.
  501. }
  502. }
  503. public ThreadState ThreadState {
  504. get {
  505. return GetState ();
  506. }
  507. }
  508. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  509. private extern void Abort_internal (object stateInfo);
  510. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  511. public void Abort ()
  512. {
  513. Abort_internal (null);
  514. }
  515. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  516. public void Abort (object stateInfo)
  517. {
  518. Abort_internal (stateInfo);
  519. }
  520. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  521. private extern void Interrupt_internal ();
  522. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  523. public void Interrupt ()
  524. {
  525. Interrupt_internal ();
  526. }
  527. // The current thread joins with 'this'. Set ms to 0 to block
  528. // until this actually exits.
  529. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  530. private extern bool Join_internal(int ms, IntPtr handle);
  531. public void Join()
  532. {
  533. Join_internal(Timeout.Infinite, system_thread_handle);
  534. }
  535. public bool Join(int millisecondsTimeout)
  536. {
  537. if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout < 0)
  538. throw new ArgumentException ("Timeout less than zero", "millisecondsTimeout");
  539. return Join_internal(millisecondsTimeout, system_thread_handle);
  540. }
  541. public bool Join(TimeSpan timeout)
  542. {
  543. // LAMESPEC: says to throw ArgumentException too
  544. int ms=Convert.ToInt32(timeout.TotalMilliseconds);
  545. if(ms < 0 || ms > Int32.MaxValue) {
  546. throw new ArgumentOutOfRangeException("timeout out of range");
  547. }
  548. return Join_internal(ms, system_thread_handle);
  549. }
  550. #if NET_1_1
  551. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  552. public extern static void MemoryBarrier ();
  553. #endif
  554. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  555. private extern void Resume_internal();
  556. #if NET_2_0
  557. [Obsolete ("")]
  558. #endif
  559. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  560. public void Resume ()
  561. {
  562. Resume_internal ();
  563. }
  564. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  565. private extern static void SpinWait_internal (int iterations);
  566. #if NET_2_0
  567. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  568. #endif
  569. public static void SpinWait (int iterations)
  570. {
  571. SpinWait_internal (iterations);
  572. }
  573. public void Start() {
  574. // propagate informations from the original thread to the new thread
  575. #if NET_2_0
  576. if (!ExecutionContext.IsFlowSuppressed ())
  577. _ec = ExecutionContext.Capture ();
  578. #else
  579. // before 2.0 this was only used for security (mostly CAS) so we
  580. // do this only if the security manager is active
  581. if (SecurityManager.SecurityEnabled)
  582. _ec = ExecutionContext.Capture ();
  583. #endif
  584. if (CurrentThread._principal != null)
  585. _principal = CurrentThread._principal;
  586. // Thread_internal creates and starts the new thread,
  587. if (Thread_internal(threadstart) == (IntPtr) 0)
  588. throw new SystemException ("Thread creation failed.");
  589. }
  590. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  591. private extern void Suspend_internal();
  592. #if NET_2_0
  593. [Obsolete ("")]
  594. #endif
  595. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  596. public void Suspend ()
  597. {
  598. Suspend_internal ();
  599. }
  600. // Closes the system thread handle
  601. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  602. private extern void Thread_free_internal(IntPtr handle);
  603. #if NET_2_0
  604. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  605. #endif
  606. ~Thread() {
  607. // Free up the handle
  608. if (system_thread_handle != (IntPtr) 0)
  609. Thread_free_internal(system_thread_handle);
  610. }
  611. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  612. extern private void SetState (ThreadState set);
  613. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  614. extern private void ClrState (ThreadState clr);
  615. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  616. extern private ThreadState GetState ();
  617. #if NET_1_1
  618. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  619. extern public static byte VolatileRead (ref byte address);
  620. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  621. extern public static double VolatileRead (ref double address);
  622. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  623. extern public static short VolatileRead (ref short address);
  624. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  625. extern public static int VolatileRead (ref int address);
  626. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  627. extern public static long VolatileRead (ref long address);
  628. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  629. extern public static IntPtr VolatileRead (ref IntPtr address);
  630. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  631. extern public static object VolatileRead (ref object address);
  632. [CLSCompliant(false)]
  633. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  634. extern public static sbyte VolatileRead (ref sbyte address);
  635. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  636. extern public static float VolatileRead (ref float address);
  637. [CLSCompliant (false)]
  638. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  639. extern public static ushort VolatileRead (ref ushort address);
  640. [CLSCompliant (false)]
  641. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  642. extern public static uint VolatileRead (ref uint address);
  643. [CLSCompliant (false)]
  644. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  645. extern public static ulong VolatileRead (ref ulong address);
  646. [CLSCompliant (false)]
  647. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  648. extern public static UIntPtr VolatileRead (ref UIntPtr address);
  649. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  650. extern public static void VolatileWrite (ref byte address, byte value);
  651. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  652. extern public static void VolatileWrite (ref double address, double value);
  653. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  654. extern public static void VolatileWrite (ref short address, short value);
  655. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  656. extern public static void VolatileWrite (ref int address, int value);
  657. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  658. extern public static void VolatileWrite (ref long address, long value);
  659. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  660. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  661. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  662. extern public static void VolatileWrite (ref object address, object value);
  663. [CLSCompliant(false)]
  664. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  665. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  666. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  667. extern public static void VolatileWrite (ref float address, float value);
  668. [CLSCompliant (false)]
  669. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  670. extern public static void VolatileWrite (ref ushort address, ushort value);
  671. [CLSCompliant (false)]
  672. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  673. extern public static void VolatileWrite (ref uint address, uint value);
  674. [CLSCompliant (false)]
  675. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  676. extern public static void VolatileWrite (ref ulong address, ulong value);
  677. [CLSCompliant (false)]
  678. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  679. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  680. #endif
  681. #if NET_2_0
  682. public Thread (ThreadStart start, int maxStackSize)
  683. {
  684. if (start == null)
  685. throw new ArgumentNullException ("start");
  686. if (maxStackSize < 131072)
  687. throw new ArgumentException ("< 128 kb", "maxStackSize");
  688. threadstart = start;
  689. stack_size = maxStackSize;
  690. managed_id = GetNewManagedId();
  691. }
  692. public Thread (ParameterizedThreadStart start)
  693. {
  694. if (start == null)
  695. throw new ArgumentNullException ("start");
  696. threadstart = start;
  697. managed_id = GetNewManagedId();
  698. }
  699. public Thread (ParameterizedThreadStart start, int maxStackSize)
  700. {
  701. if (start == null)
  702. throw new ArgumentNullException ("start");
  703. if (maxStackSize < 131072)
  704. throw new ArgumentException ("< 128 kb", "maxStackSize");
  705. threadstart = start;
  706. stack_size = maxStackSize;
  707. managed_id = GetNewManagedId();
  708. }
  709. [MonoTODO ("limited to CompressedStack support")]
  710. // FIXME: We share the _ec object between appdomains
  711. public ExecutionContext ExecutionContext {
  712. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  713. get {
  714. if (_ec == null)
  715. _ec = new ExecutionContext ();
  716. return _ec;
  717. }
  718. }
  719. public int ManagedThreadId {
  720. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  721. get { return managed_id; }
  722. }
  723. [MonoTODO("Not implemented")]
  724. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  725. public static void BeginCriticalRegion ()
  726. {
  727. throw new NotImplementedException ();
  728. }
  729. [MonoTODO("Not implemented")]
  730. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  731. public static void EndCriticalRegion ()
  732. {
  733. throw new NotImplementedException ();
  734. }
  735. [MonoTODO("Not implemented")]
  736. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  737. public static void BeginThreadAffinity ()
  738. {
  739. throw new NotImplementedException ();
  740. }
  741. [MonoTODO("Not implemented")]
  742. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  743. public static void EndThreadAffinity ()
  744. {
  745. throw new NotImplementedException ();
  746. }
  747. public ApartmentState GetApartmentState ()
  748. {
  749. return (ApartmentState)apartment_state;
  750. }
  751. public void SetApartmentState (ApartmentState state)
  752. {
  753. if (!TrySetApartmentState (state))
  754. throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
  755. }
  756. public bool TrySetApartmentState (ApartmentState state)
  757. {
  758. if ((ThreadState & ThreadState.Unstarted) == 0)
  759. throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
  760. if ((ApartmentState)apartment_state != ApartmentState.Unknown)
  761. return false;
  762. apartment_state = (byte)state;
  763. return true;
  764. }
  765. [ComVisible (false)]
  766. public override int GetHashCode ()
  767. {
  768. return managed_id;
  769. }
  770. public void Start (object parameter)
  771. {
  772. start_obj = parameter;
  773. Start ();
  774. }
  775. #else
  776. internal ExecutionContext ExecutionContext {
  777. get {
  778. if (_ec == null)
  779. _ec = new ExecutionContext ();
  780. return _ec;
  781. }
  782. }
  783. #endif
  784. // NOTE: This method doesn't show in the class library status page because
  785. // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
  786. // But it's there!
  787. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  788. [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
  789. #if NET_2_0
  790. [Obsolete ("see CompressedStack class")]
  791. #endif
  792. #if NET_1_1
  793. public
  794. #else
  795. internal
  796. #endif
  797. CompressedStack GetCompressedStack ()
  798. {
  799. // Note: returns null if no CompressedStack has been set.
  800. // However CompressedStack.GetCompressedStack returns an
  801. // (empty?) CompressedStack instance.
  802. CompressedStack cs = ExecutionContext.SecurityContext.CompressedStack;
  803. return ((cs == null) || cs.IsEmpty ()) ? null : cs.CreateCopy ();
  804. }
  805. // NOTE: This method doesn't show in the class library status page because
  806. // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
  807. // But it's there!
  808. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  809. [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
  810. #if NET_2_0
  811. [Obsolete ("see CompressedStack class")]
  812. #endif
  813. #if NET_1_1
  814. public
  815. #else
  816. internal
  817. #endif
  818. void SetCompressedStack (CompressedStack stack)
  819. {
  820. ExecutionContext.SecurityContext.CompressedStack = stack;
  821. }
  822. #if NET_1_1
  823. void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  824. {
  825. throw new NotImplementedException ();
  826. }
  827. void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  828. {
  829. throw new NotImplementedException ();
  830. }
  831. void _Thread.GetTypeInfoCount (out uint pcTInfo)
  832. {
  833. throw new NotImplementedException ();
  834. }
  835. void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
  836. IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  837. {
  838. throw new NotImplementedException ();
  839. }
  840. #endif
  841. }
  842. }