Thread.cs 29 KB

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