Thread.cs 28 KB

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