Thread.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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.Generic;
  39. using System.Reflection;
  40. using System.Security;
  41. using System.Diagnostics;
  42. using System.Runtime.ConstrainedExecution;
  43. namespace System.Threading {
  44. [StructLayout (LayoutKind.Sequential)]
  45. sealed class InternalThread : CriticalFinalizerObject {
  46. #pragma warning disable 169, 414, 649
  47. #region Sync with metadata/object-internals.h
  48. int lock_thread_id;
  49. // stores a thread handle
  50. IntPtr handle;
  51. IntPtr native_handle; // used only on Win32
  52. IntPtr unused3;
  53. /* accessed only from unmanaged code */
  54. private IntPtr name;
  55. private int name_len;
  56. private ThreadState state;
  57. private object abort_exc;
  58. private int abort_state_handle;
  59. /* thread_id is only accessed from unmanaged code */
  60. internal Int64 thread_id;
  61. private IntPtr debugger_thread; // FIXME switch to bool as soon as CI testing with corlib version bump works
  62. private UIntPtr static_data; /* GC-tracked */
  63. private IntPtr runtime_thread_info;
  64. /* current System.Runtime.Remoting.Contexts.Context instance
  65. keep as an object to avoid triggering its class constructor when not needed */
  66. private object current_appcontext;
  67. private object root_domain_thread;
  68. internal byte[] _serialized_principal;
  69. internal int _serialized_principal_version;
  70. private IntPtr appdomain_refs;
  71. private int interruption_requested;
  72. private IntPtr synch_cs;
  73. internal bool threadpool_thread;
  74. private bool thread_interrupt_requested;
  75. /* These are used from managed code */
  76. internal int stack_size;
  77. internal byte apartment_state;
  78. internal volatile int critical_region_level;
  79. internal int managed_id;
  80. private int small_id;
  81. private IntPtr manage_callback;
  82. private IntPtr unused4;
  83. private IntPtr flags;
  84. private IntPtr thread_pinning_ref;
  85. private IntPtr abort_protected_block_count;
  86. private int priority = (int) ThreadPriority.Normal;
  87. private IntPtr owned_mutex;
  88. private IntPtr suspended_event;
  89. private int self_suspended;
  90. /*
  91. * These fields are used to avoid having to increment corlib versions
  92. * when a new field is added to the unmanaged MonoThread structure.
  93. */
  94. private IntPtr unused1;
  95. private IntPtr unused2;
  96. /* This is used only to check that we are in sync between the representation
  97. * of MonoInternalThread in native and InternalThread in managed
  98. *
  99. * DO NOT RENAME! DO NOT ADD FIELDS AFTER! */
  100. private IntPtr last;
  101. #endregion
  102. #pragma warning restore 169, 414, 649
  103. // Closes the system thread handle
  104. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  105. private extern void Thread_free_internal();
  106. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  107. ~InternalThread() {
  108. Thread_free_internal();
  109. }
  110. }
  111. [StructLayout (LayoutKind.Sequential)]
  112. public sealed partial class Thread {
  113. #pragma warning disable 414
  114. #region Sync with metadata/object-internals.h
  115. private InternalThread internal_thread;
  116. object m_ThreadStartArg;
  117. object pending_exception;
  118. #endregion
  119. #pragma warning restore 414
  120. IPrincipal principal;
  121. int principal_version;
  122. // the name of current_thread is
  123. // important because they are used by the runtime.
  124. [ThreadStatic]
  125. static Thread current_thread;
  126. // can be both a ThreadStart and a ParameterizedThreadStart
  127. private MulticastDelegate m_Delegate;
  128. private ExecutionContext m_ExecutionContext; // this call context follows the logical thread
  129. private bool m_ExecutionContextBelongsToOuterScope;
  130. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  131. private extern void ConstructInternalThread ();
  132. private InternalThread Internal {
  133. get {
  134. if (internal_thread == null)
  135. ConstructInternalThread ();
  136. return internal_thread;
  137. }
  138. }
  139. public static Context CurrentContext {
  140. [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
  141. get {
  142. return(AppDomain.InternalGetContext ());
  143. }
  144. }
  145. /*
  146. * These two methods return an array in the target
  147. * domain with the same content as the argument. If
  148. * the argument is already in the target domain, then
  149. * the argument is returned, otherwise a copy.
  150. */
  151. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  152. private extern static byte[] ByteArrayToRootDomain (byte[] arr);
  153. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  154. private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
  155. static void DeserializePrincipal (Thread th)
  156. {
  157. MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
  158. int type = ms.ReadByte ();
  159. if (type == 0) {
  160. BinaryFormatter bf = new BinaryFormatter ();
  161. th.principal = (IPrincipal) bf.Deserialize (ms);
  162. th.principal_version = th.Internal._serialized_principal_version;
  163. } else if (type == 1) {
  164. BinaryReader reader = new BinaryReader (ms);
  165. string name = reader.ReadString ();
  166. string auth_type = reader.ReadString ();
  167. int n_roles = reader.ReadInt32 ();
  168. string [] roles = null;
  169. if (n_roles >= 0) {
  170. roles = new string [n_roles];
  171. for (int i = 0; i < n_roles; i++)
  172. roles [i] = reader.ReadString ();
  173. }
  174. th.principal = new GenericPrincipal (new GenericIdentity (name, auth_type), roles);
  175. } else if (type == 2 || type == 3) {
  176. string [] roles = type == 2 ? null : new string [0];
  177. th.principal = new GenericPrincipal (new GenericIdentity ("", ""), roles);
  178. }
  179. }
  180. static void SerializePrincipal (Thread th, IPrincipal value)
  181. {
  182. MemoryStream ms = new MemoryStream ();
  183. bool done = false;
  184. if (value.GetType () == typeof (GenericPrincipal)) {
  185. GenericPrincipal gp = (GenericPrincipal) value;
  186. if (gp.Identity != null && gp.Identity.GetType () == typeof (GenericIdentity)) {
  187. GenericIdentity id = (GenericIdentity) gp.Identity;
  188. if (id.Name == "" && id.AuthenticationType == "") {
  189. if (gp.Roles == null) {
  190. ms.WriteByte (2);
  191. done = true;
  192. } else if (gp.Roles.Length == 0) {
  193. ms.WriteByte (3);
  194. done = true;
  195. }
  196. } else {
  197. ms.WriteByte (1);
  198. BinaryWriter br = new BinaryWriter (ms);
  199. br.Write (gp.Identity.Name);
  200. br.Write (gp.Identity.AuthenticationType);
  201. string [] roles = gp.Roles;
  202. if (roles == null) {
  203. br.Write ((int) (-1));
  204. } else {
  205. br.Write (roles.Length);
  206. foreach (string s in roles) {
  207. br.Write (s);
  208. }
  209. }
  210. br.Flush ();
  211. done = true;
  212. }
  213. }
  214. }
  215. if (!done) {
  216. ms.WriteByte (0);
  217. BinaryFormatter bf = new BinaryFormatter ();
  218. try {
  219. bf.Serialize (ms, value);
  220. } catch {}
  221. }
  222. th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
  223. }
  224. public static IPrincipal CurrentPrincipal {
  225. get {
  226. Thread th = CurrentThread;
  227. if (th.principal_version != th.Internal._serialized_principal_version)
  228. th.principal = null;
  229. if (th.principal != null)
  230. return th.principal;
  231. if (th.Internal._serialized_principal != null) {
  232. try {
  233. DeserializePrincipal (th);
  234. return th.principal;
  235. } catch {}
  236. }
  237. th.principal = GetDomain ().DefaultPrincipal;
  238. th.principal_version = th.Internal._serialized_principal_version;
  239. return th.principal;
  240. }
  241. [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
  242. set {
  243. Thread th = CurrentThread;
  244. if (value != GetDomain ().DefaultPrincipal) {
  245. ++th.Internal._serialized_principal_version;
  246. try {
  247. SerializePrincipal (th, value);
  248. } catch (Exception) {
  249. th.Internal._serialized_principal = null;
  250. }
  251. th.principal_version = th.Internal._serialized_principal_version;
  252. } else {
  253. th.Internal._serialized_principal = null;
  254. }
  255. th.principal = value;
  256. }
  257. }
  258. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  259. private extern static Thread GetCurrentThread ();
  260. public static Thread CurrentThread {
  261. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  262. get {
  263. Thread current = current_thread;
  264. if (current != null)
  265. return current;
  266. // This will set the current_thread tls variable
  267. return GetCurrentThread ();
  268. }
  269. }
  270. internal static int CurrentThreadId {
  271. get {
  272. return (int)(CurrentThread.internal_thread.thread_id);
  273. }
  274. }
  275. public static AppDomain GetDomain() {
  276. return AppDomain.CurrentDomain;
  277. }
  278. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  279. public extern static int GetDomainID();
  280. // Returns the system thread handle
  281. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  282. private extern bool Thread_internal (MulticastDelegate start);
  283. private Thread (InternalThread it) {
  284. internal_thread = it;
  285. }
  286. // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
  287. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  288. ~Thread ()
  289. {
  290. }
  291. [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
  292. public ApartmentState ApartmentState {
  293. get {
  294. ValidateThreadState ();
  295. return (ApartmentState)Internal.apartment_state;
  296. }
  297. set {
  298. ValidateThreadState ();
  299. TrySetApartmentState (value);
  300. }
  301. }
  302. public bool IsThreadPoolThread {
  303. get {
  304. return IsThreadPoolThreadInternal;
  305. }
  306. }
  307. internal bool IsThreadPoolThreadInternal {
  308. get {
  309. return Internal.threadpool_thread;
  310. }
  311. set {
  312. Internal.threadpool_thread = value;
  313. }
  314. }
  315. public bool IsAlive {
  316. get {
  317. ThreadState curstate = GetState (Internal);
  318. if((curstate & ThreadState.Aborted) != 0 ||
  319. (curstate & ThreadState.Stopped) != 0 ||
  320. (curstate & ThreadState.Unstarted) != 0) {
  321. return(false);
  322. } else {
  323. return(true);
  324. }
  325. }
  326. }
  327. public bool IsBackground {
  328. get {
  329. var state = ValidateThreadState ();
  330. return (state & ThreadState.Background) != 0;
  331. }
  332. set {
  333. ValidateThreadState ();
  334. if (value) {
  335. SetState (Internal, ThreadState.Background);
  336. } else {
  337. ClrState (Internal, ThreadState.Background);
  338. }
  339. }
  340. }
  341. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  342. private extern static string GetName_internal (InternalThread thread);
  343. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  344. private extern static void SetName_internal (InternalThread thread, String name);
  345. /*
  346. * The thread name must be shared by appdomains, so it is stored in
  347. * unmanaged code.
  348. */
  349. public string Name {
  350. get {
  351. return GetName_internal (Internal);
  352. }
  353. set {
  354. SetName_internal (Internal, value);
  355. }
  356. }
  357. public ThreadState ThreadState {
  358. get {
  359. return GetState (Internal);
  360. }
  361. }
  362. #if MONO_FEATURE_THREAD_ABORT
  363. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  364. private extern static void Abort_internal (InternalThread thread, object stateInfo);
  365. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  366. public void Abort ()
  367. {
  368. Abort_internal (Internal, null);
  369. }
  370. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  371. public void Abort (object stateInfo)
  372. {
  373. Abort_internal (Internal, stateInfo);
  374. }
  375. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  376. extern object GetAbortExceptionState ();
  377. internal object AbortReason {
  378. get {
  379. return GetAbortExceptionState ();
  380. }
  381. }
  382. void ClearAbortReason ()
  383. {
  384. }
  385. #else
  386. [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
  387. public void Abort ()
  388. {
  389. throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
  390. }
  391. [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
  392. public void Abort (object stateInfo)
  393. {
  394. throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
  395. }
  396. [Obsolete ("Thread.ResetAbort is not supported on the current platform.", true)]
  397. public static void ResetAbort ()
  398. {
  399. throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
  400. }
  401. internal object AbortReason {
  402. get {
  403. throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
  404. }
  405. }
  406. #endif // MONO_FEATURE_THREAD_ABORT
  407. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  408. private extern static void SpinWait_nop ();
  409. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  410. public static void SpinWait (int iterations)
  411. {
  412. if (iterations < 0)
  413. return;
  414. while (iterations-- > 0)
  415. {
  416. SpinWait_nop ();
  417. }
  418. }
  419. void StartInternal (IPrincipal principal, ref StackCrawlMark stackMark)
  420. {
  421. #if FEATURE_ROLE_BASED_SECURITY
  422. Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
  423. #endif
  424. // Thread_internal creates and starts the new thread,
  425. if (!Thread_internal(m_Delegate))
  426. throw new SystemException ("Thread creation failed.");
  427. m_ThreadStartArg = null;
  428. }
  429. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  430. extern private static void SetState (InternalThread thread, ThreadState set);
  431. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  432. extern private static void ClrState (InternalThread thread, ThreadState clr);
  433. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  434. extern private static ThreadState GetState (InternalThread thread);
  435. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  436. extern public static byte VolatileRead (ref byte address);
  437. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  438. extern public static double VolatileRead (ref double address);
  439. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  440. extern public static short VolatileRead (ref short address);
  441. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  442. extern public static int VolatileRead (ref int address);
  443. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  444. extern public static long VolatileRead (ref long address);
  445. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  446. extern public static IntPtr VolatileRead (ref IntPtr address);
  447. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  448. extern public static object VolatileRead (ref object address);
  449. [CLSCompliant(false)]
  450. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  451. extern public static sbyte VolatileRead (ref sbyte address);
  452. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  453. extern public static float VolatileRead (ref float address);
  454. [CLSCompliant (false)]
  455. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  456. extern public static ushort VolatileRead (ref ushort address);
  457. [CLSCompliant (false)]
  458. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  459. extern public static uint VolatileRead (ref uint address);
  460. [CLSCompliant (false)]
  461. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  462. extern public static ulong VolatileRead (ref ulong address);
  463. [CLSCompliant (false)]
  464. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  465. extern public static UIntPtr VolatileRead (ref UIntPtr address);
  466. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  467. extern public static void VolatileWrite (ref byte address, byte value);
  468. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  469. extern public static void VolatileWrite (ref double address, double value);
  470. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  471. extern public static void VolatileWrite (ref short address, short value);
  472. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  473. extern public static void VolatileWrite (ref int address, int value);
  474. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  475. extern public static void VolatileWrite (ref long address, long value);
  476. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  477. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  478. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  479. extern public static void VolatileWrite (ref object address, object value);
  480. [CLSCompliant(false)]
  481. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  482. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  483. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  484. extern public static void VolatileWrite (ref float address, float value);
  485. [CLSCompliant (false)]
  486. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  487. extern public static void VolatileWrite (ref ushort address, ushort value);
  488. [CLSCompliant (false)]
  489. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  490. extern public static void VolatileWrite (ref uint address, uint value);
  491. [CLSCompliant (false)]
  492. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  493. extern public static void VolatileWrite (ref ulong address, ulong value);
  494. [CLSCompliant (false)]
  495. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  496. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  497. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  498. extern static int SystemMaxStackStize ();
  499. static int GetProcessDefaultStackSize (int maxStackSize)
  500. {
  501. if (maxStackSize == 0)
  502. return 0;
  503. if (maxStackSize < 131072) // make sure stack is at least 128k big
  504. return 131072;
  505. int page_size = Environment.GetPageSize ();
  506. if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
  507. maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
  508. /* Respect the max stack size imposed by the system*/
  509. return Math.Min (maxStackSize, SystemMaxStackStize ());
  510. }
  511. void SetStart (MulticastDelegate start, int maxStackSize)
  512. {
  513. m_Delegate = start;
  514. Internal.stack_size = maxStackSize;
  515. }
  516. public int ManagedThreadId {
  517. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  518. get {
  519. return Internal.managed_id;
  520. }
  521. }
  522. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  523. public static void BeginCriticalRegion ()
  524. {
  525. CurrentThread.Internal.critical_region_level++;
  526. }
  527. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  528. public static void EndCriticalRegion ()
  529. {
  530. CurrentThread.Internal.critical_region_level--;
  531. }
  532. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  533. public static void BeginThreadAffinity ()
  534. {
  535. // Managed and native threads are currently bound together.
  536. }
  537. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  538. public static void EndThreadAffinity ()
  539. {
  540. // Managed and native threads are currently bound together.
  541. }
  542. public ApartmentState GetApartmentState ()
  543. {
  544. ValidateThreadState ();
  545. return (ApartmentState)Internal.apartment_state;
  546. }
  547. public void SetApartmentState (ApartmentState state)
  548. {
  549. if (!TrySetApartmentState (state))
  550. throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
  551. }
  552. public bool TrySetApartmentState (ApartmentState state)
  553. {
  554. if ((ThreadState & ThreadState.Unstarted) == 0)
  555. throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
  556. if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown &&
  557. (ApartmentState)Internal.apartment_state != state)
  558. return false;
  559. Internal.apartment_state = (byte)state;
  560. return true;
  561. }
  562. [ComVisible (false)]
  563. public override int GetHashCode ()
  564. {
  565. return ManagedThreadId;
  566. }
  567. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  568. internal static extern void GetStackTraces (out Thread[] threads, out object[] stack_frames);
  569. // This is a mono extension to gather the stack traces for all running threads
  570. internal static Dictionary<Thread, StackTrace> Mono_GetStackTraces () {
  571. Thread[] threads;
  572. object[] stack_frames;
  573. GetStackTraces (out threads, out stack_frames);
  574. var res = new Dictionary<Thread, StackTrace> ();
  575. for (int i = 0; i < threads.Length; ++i)
  576. res [threads [i]] = new StackTrace ((StackFrame[])stack_frames [i]);
  577. return res;
  578. }
  579. #if !MONO_FEATURE_THREAD_SUSPEND_RESUME
  580. [Obsolete ("Thread.Suspend is not supported on the current platform.", true)]
  581. public void Suspend ()
  582. {
  583. throw new PlatformNotSupportedException ("Thread.Suspend is not supported on the current platform.");
  584. }
  585. [Obsolete ("Thread.Resume is not supported on the current platform.", true)]
  586. public void Resume ()
  587. {
  588. throw new PlatformNotSupportedException ("Thread.Resume is not supported on the current platform.");
  589. }
  590. #endif
  591. public void DisableComObjectEagerCleanup ()
  592. {
  593. throw new PlatformNotSupportedException ();
  594. }
  595. ThreadState ValidateThreadState ()
  596. {
  597. var state = GetState (Internal);
  598. if ((state & ThreadState.Stopped) != 0)
  599. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  600. return state;
  601. }
  602. }
  603. }