Thread.cs 21 KB

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