Thread.cs 31 KB

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