Thread.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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. var logicalPrincipal = th.GetExecutionContextReader().LogicalCallContext.Principal;
  228. if (logicalPrincipal != null)
  229. return logicalPrincipal;
  230. if (th.principal_version != th.Internal._serialized_principal_version)
  231. th.principal = null;
  232. if (th.principal != null)
  233. return th.principal;
  234. if (th.Internal._serialized_principal != null) {
  235. try {
  236. DeserializePrincipal (th);
  237. return th.principal;
  238. } catch {}
  239. }
  240. th.principal = GetDomain ().DefaultPrincipal;
  241. th.principal_version = th.Internal._serialized_principal_version;
  242. return th.principal;
  243. }
  244. [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
  245. set {
  246. Thread th = CurrentThread;
  247. th.GetMutableExecutionContext().LogicalCallContext.Principal = value;
  248. if (value != GetDomain ().DefaultPrincipal) {
  249. ++th.Internal._serialized_principal_version;
  250. try {
  251. SerializePrincipal (th, value);
  252. } catch (Exception) {
  253. th.Internal._serialized_principal = null;
  254. }
  255. th.principal_version = th.Internal._serialized_principal_version;
  256. } else {
  257. th.Internal._serialized_principal = null;
  258. }
  259. th.principal = value;
  260. }
  261. }
  262. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  263. private extern static Thread GetCurrentThread ();
  264. public static Thread CurrentThread {
  265. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  266. get {
  267. Thread current = current_thread;
  268. if (current != null)
  269. return current;
  270. // This will set the current_thread tls variable
  271. return GetCurrentThread ();
  272. }
  273. }
  274. internal static int CurrentThreadId {
  275. get {
  276. return (int)(CurrentThread.internal_thread.thread_id);
  277. }
  278. }
  279. public static AppDomain GetDomain() {
  280. return AppDomain.CurrentDomain;
  281. }
  282. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  283. public extern static int GetDomainID();
  284. // Returns the system thread handle
  285. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  286. private extern bool Thread_internal (MulticastDelegate start);
  287. private Thread (InternalThread it) {
  288. internal_thread = it;
  289. }
  290. // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
  291. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  292. ~Thread ()
  293. {
  294. }
  295. [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
  296. public ApartmentState ApartmentState {
  297. get {
  298. ValidateThreadState ();
  299. return (ApartmentState)Internal.apartment_state;
  300. }
  301. set {
  302. ValidateThreadState ();
  303. TrySetApartmentState (value);
  304. }
  305. }
  306. public bool IsThreadPoolThread {
  307. get {
  308. return IsThreadPoolThreadInternal;
  309. }
  310. }
  311. internal bool IsThreadPoolThreadInternal {
  312. get {
  313. return Internal.threadpool_thread;
  314. }
  315. set {
  316. Internal.threadpool_thread = value;
  317. }
  318. }
  319. public bool IsAlive {
  320. get {
  321. ThreadState curstate = GetState (Internal);
  322. if((curstate & ThreadState.Aborted) != 0 ||
  323. (curstate & ThreadState.Stopped) != 0 ||
  324. (curstate & ThreadState.Unstarted) != 0) {
  325. return(false);
  326. } else {
  327. return(true);
  328. }
  329. }
  330. }
  331. public bool IsBackground {
  332. get {
  333. var state = ValidateThreadState ();
  334. return (state & ThreadState.Background) != 0;
  335. }
  336. set {
  337. ValidateThreadState ();
  338. if (value) {
  339. SetState (Internal, ThreadState.Background);
  340. } else {
  341. ClrState (Internal, ThreadState.Background);
  342. }
  343. }
  344. }
  345. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  346. private extern static string GetName_internal (InternalThread thread);
  347. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  348. private extern static void SetName_internal (InternalThread thread, String name);
  349. /*
  350. * The thread name must be shared by appdomains, so it is stored in
  351. * unmanaged code.
  352. */
  353. public string Name {
  354. get {
  355. return GetName_internal (Internal);
  356. }
  357. set {
  358. SetName_internal (Internal, value);
  359. }
  360. }
  361. public ThreadState ThreadState {
  362. get {
  363. return GetState (Internal);
  364. }
  365. }
  366. #if MONO_FEATURE_THREAD_ABORT
  367. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  368. private extern static void Abort_internal (InternalThread thread, object stateInfo);
  369. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  370. public void Abort ()
  371. {
  372. Abort_internal (Internal, null);
  373. }
  374. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  375. public void Abort (object stateInfo)
  376. {
  377. Abort_internal (Internal, stateInfo);
  378. }
  379. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  380. extern object GetAbortExceptionState ();
  381. internal object AbortReason {
  382. get {
  383. return GetAbortExceptionState ();
  384. }
  385. }
  386. void ClearAbortReason ()
  387. {
  388. }
  389. #else
  390. [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
  391. public void Abort ()
  392. {
  393. throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
  394. }
  395. [Obsolete ("Thread.Abort is not supported on the current platform.", true)]
  396. public void Abort (object stateInfo)
  397. {
  398. throw new PlatformNotSupportedException ("Thread.Abort is not supported on the current platform.");
  399. }
  400. [Obsolete ("Thread.ResetAbort is not supported on the current platform.", true)]
  401. public static void ResetAbort ()
  402. {
  403. throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
  404. }
  405. internal object AbortReason {
  406. get {
  407. throw new PlatformNotSupportedException ("Thread.ResetAbort is not supported on the current platform.");
  408. }
  409. }
  410. #endif // MONO_FEATURE_THREAD_ABORT
  411. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  412. private extern static void SpinWait_nop ();
  413. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  414. public static void SpinWait (int iterations)
  415. {
  416. if (iterations < 0)
  417. return;
  418. while (iterations-- > 0)
  419. {
  420. SpinWait_nop ();
  421. }
  422. }
  423. void StartInternal (IPrincipal principal, ref StackCrawlMark stackMark)
  424. {
  425. #if FEATURE_ROLE_BASED_SECURITY
  426. Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
  427. #endif
  428. // Thread_internal creates and starts the new thread,
  429. if (!Thread_internal(m_Delegate))
  430. throw new SystemException ("Thread creation failed.");
  431. m_ThreadStartArg = null;
  432. }
  433. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  434. extern private static void SetState (InternalThread thread, ThreadState set);
  435. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  436. extern private static void ClrState (InternalThread thread, ThreadState clr);
  437. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  438. extern private static ThreadState GetState (InternalThread thread);
  439. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  440. extern public static byte VolatileRead (ref byte address);
  441. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  442. extern public static double VolatileRead (ref double address);
  443. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  444. extern public static short VolatileRead (ref short address);
  445. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  446. extern public static int VolatileRead (ref int address);
  447. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  448. extern public static long VolatileRead (ref long address);
  449. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  450. extern public static IntPtr VolatileRead (ref IntPtr address);
  451. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  452. extern public static object VolatileRead (ref object address);
  453. [CLSCompliant(false)]
  454. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  455. extern public static sbyte VolatileRead (ref sbyte address);
  456. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  457. extern public static float VolatileRead (ref float address);
  458. [CLSCompliant (false)]
  459. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  460. extern public static ushort VolatileRead (ref ushort address);
  461. [CLSCompliant (false)]
  462. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  463. extern public static uint VolatileRead (ref uint address);
  464. [CLSCompliant (false)]
  465. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  466. extern public static ulong VolatileRead (ref ulong address);
  467. [CLSCompliant (false)]
  468. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  469. extern public static UIntPtr VolatileRead (ref UIntPtr address);
  470. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  471. extern public static void VolatileWrite (ref byte address, byte value);
  472. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  473. extern public static void VolatileWrite (ref double address, double value);
  474. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  475. extern public static void VolatileWrite (ref short address, short value);
  476. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  477. extern public static void VolatileWrite (ref int address, int value);
  478. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  479. extern public static void VolatileWrite (ref long address, long value);
  480. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  481. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  482. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  483. extern public static void VolatileWrite (ref object address, object value);
  484. [CLSCompliant(false)]
  485. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  486. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  487. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  488. extern public static void VolatileWrite (ref float address, float value);
  489. [CLSCompliant (false)]
  490. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  491. extern public static void VolatileWrite (ref ushort address, ushort value);
  492. [CLSCompliant (false)]
  493. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  494. extern public static void VolatileWrite (ref uint address, uint value);
  495. [CLSCompliant (false)]
  496. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  497. extern public static void VolatileWrite (ref ulong address, ulong value);
  498. [CLSCompliant (false)]
  499. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  500. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  501. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  502. extern static int SystemMaxStackStize ();
  503. static int GetProcessDefaultStackSize (int maxStackSize)
  504. {
  505. if (maxStackSize == 0)
  506. return 0;
  507. if (maxStackSize < 131072) // make sure stack is at least 128k big
  508. return 131072;
  509. int page_size = Environment.GetPageSize ();
  510. if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
  511. maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
  512. /* Respect the max stack size imposed by the system*/
  513. return Math.Min (maxStackSize, SystemMaxStackStize ());
  514. }
  515. void SetStart (MulticastDelegate start, int maxStackSize)
  516. {
  517. m_Delegate = start;
  518. Internal.stack_size = maxStackSize;
  519. }
  520. public int ManagedThreadId {
  521. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  522. get {
  523. return Internal.managed_id;
  524. }
  525. }
  526. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  527. public static void BeginCriticalRegion ()
  528. {
  529. CurrentThread.Internal.critical_region_level++;
  530. }
  531. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  532. public static void EndCriticalRegion ()
  533. {
  534. CurrentThread.Internal.critical_region_level--;
  535. }
  536. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  537. public static void BeginThreadAffinity ()
  538. {
  539. // Managed and native threads are currently bound together.
  540. }
  541. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  542. public static void EndThreadAffinity ()
  543. {
  544. // Managed and native threads are currently bound together.
  545. }
  546. public ApartmentState GetApartmentState ()
  547. {
  548. ValidateThreadState ();
  549. return (ApartmentState)Internal.apartment_state;
  550. }
  551. public void SetApartmentState (ApartmentState state)
  552. {
  553. if (!TrySetApartmentState (state))
  554. throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
  555. }
  556. public bool TrySetApartmentState (ApartmentState state)
  557. {
  558. if ((ThreadState & ThreadState.Unstarted) == 0)
  559. throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
  560. if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown &&
  561. (ApartmentState)Internal.apartment_state != state)
  562. return false;
  563. Internal.apartment_state = (byte)state;
  564. return true;
  565. }
  566. [ComVisible (false)]
  567. public override int GetHashCode ()
  568. {
  569. return ManagedThreadId;
  570. }
  571. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  572. internal static extern void GetStackTraces (out Thread[] threads, out object[] stack_frames);
  573. // This is a mono extension to gather the stack traces for all running threads
  574. internal static Dictionary<Thread, StackTrace> Mono_GetStackTraces () {
  575. Thread[] threads;
  576. object[] stack_frames;
  577. GetStackTraces (out threads, out stack_frames);
  578. var res = new Dictionary<Thread, StackTrace> ();
  579. for (int i = 0; i < threads.Length; ++i)
  580. res [threads [i]] = new StackTrace ((StackFrame[])stack_frames [i]);
  581. return res;
  582. }
  583. #if !MONO_FEATURE_THREAD_SUSPEND_RESUME
  584. [Obsolete ("Thread.Suspend is not supported on the current platform.", true)]
  585. public void Suspend ()
  586. {
  587. throw new PlatformNotSupportedException ("Thread.Suspend is not supported on the current platform.");
  588. }
  589. [Obsolete ("Thread.Resume is not supported on the current platform.", true)]
  590. public void Resume ()
  591. {
  592. throw new PlatformNotSupportedException ("Thread.Resume is not supported on the current platform.");
  593. }
  594. #endif
  595. public void DisableComObjectEagerCleanup ()
  596. {
  597. throw new PlatformNotSupportedException ();
  598. }
  599. ThreadState ValidateThreadState ()
  600. {
  601. var state = GetState (Internal);
  602. if ((state & ThreadState.Stopped) != 0)
  603. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  604. return state;
  605. }
  606. }
  607. }