Thread.cs 32 KB

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