Thread.cs 29 KB

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