Thread.cs 28 KB

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