Thread.cs 29 KB

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