Thread.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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.Runtime.ConstrainedExecution;
  42. namespace System.Threading {
  43. [StructLayout (LayoutKind.Sequential)]
  44. sealed class InternalThread : CriticalFinalizerObject {
  45. #pragma warning disable 169, 414, 649
  46. #region Sync with metadata/object-internals.h
  47. int lock_thread_id;
  48. // stores a thread handle
  49. internal IntPtr system_thread_handle;
  50. /* Note this is an opaque object (an array), not a CultureInfo */
  51. private object cached_culture_info;
  52. /* accessed only from unmanaged code */
  53. private IntPtr name;
  54. private int name_len;
  55. private ThreadState state;
  56. private object abort_exc;
  57. private int abort_state_handle;
  58. /* thread_id is only accessed from unmanaged code */
  59. internal Int64 thread_id;
  60. /* start_notify is used by the runtime to signal that Start()
  61. * is ok to return
  62. */
  63. private IntPtr start_notify;
  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 pending_exception;
  71. private object root_domain_thread;
  72. internal byte[] _serialized_principal;
  73. internal int _serialized_principal_version;
  74. private IntPtr appdomain_refs;
  75. private int interruption_requested;
  76. private IntPtr synch_cs;
  77. internal bool threadpool_thread;
  78. private bool thread_interrupt_requested;
  79. /* These are used from managed code */
  80. internal int stack_size;
  81. internal byte apartment_state;
  82. internal volatile int critical_region_level;
  83. internal int managed_id;
  84. private int small_id;
  85. private IntPtr manage_callback;
  86. private IntPtr interrupt_on_stop;
  87. private IntPtr flags;
  88. private IntPtr thread_pinning_ref;
  89. private IntPtr async_invoke_method;
  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. #endregion
  97. #pragma warning restore 169, 414, 649
  98. // Closes the system thread handle
  99. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  100. private extern void Thread_free_internal(IntPtr handle);
  101. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  102. ~InternalThread() {
  103. Thread_free_internal(system_thread_handle);
  104. }
  105. }
  106. [StructLayout (LayoutKind.Sequential)]
  107. public sealed partial class Thread {
  108. #pragma warning disable 414
  109. #region Sync with metadata/object-internals.h
  110. private InternalThread internal_thread;
  111. object m_ThreadStartArg;
  112. private ExecutionContext ec_to_set;
  113. #endregion
  114. #pragma warning restore 414
  115. IPrincipal principal;
  116. int principal_version;
  117. bool current_culture_set;
  118. bool current_ui_culture_set;
  119. CultureInfo current_culture;
  120. CultureInfo current_ui_culture;
  121. // the name of current_thread and _ec is
  122. // important because they are used by the runtime.
  123. [ThreadStatic]
  124. static Thread current_thread;
  125. /* The actual ExecutionContext of the thread. It's
  126. ThreadStatic so that it's not shared between
  127. AppDomains. */
  128. [ThreadStatic]
  129. static ExecutionContext _ec;
  130. static internal CultureInfo default_culture;
  131. static internal CultureInfo default_ui_culture;
  132. // can be both a ThreadStart and a ParameterizedThreadStart
  133. private MulticastDelegate m_Delegate;
  134. private ExecutionContext m_ExecutionContext; // this call context follows the logical thread
  135. private bool m_ExecutionContextBelongsToOuterScope;
  136. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  137. private extern void ConstructInternalThread ();
  138. private InternalThread Internal {
  139. get {
  140. if (internal_thread == null)
  141. ConstructInternalThread ();
  142. return internal_thread;
  143. }
  144. }
  145. public static Context CurrentContext {
  146. [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
  147. get {
  148. return(AppDomain.InternalGetContext ());
  149. }
  150. }
  151. /*
  152. * These two methods return an array in the target
  153. * domain with the same content as the argument. If
  154. * the argument is already in the target domain, then
  155. * the argument is returned, otherwise a copy.
  156. */
  157. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  158. private extern static byte[] ByteArrayToRootDomain (byte[] arr);
  159. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  160. private extern static byte[] ByteArrayToCurrentDomain (byte[] arr);
  161. static void DeserializePrincipal (Thread th)
  162. {
  163. MemoryStream ms = new MemoryStream (ByteArrayToCurrentDomain (th.Internal._serialized_principal));
  164. int type = ms.ReadByte ();
  165. if (type == 0) {
  166. BinaryFormatter bf = new BinaryFormatter ();
  167. th.principal = (IPrincipal) bf.Deserialize (ms);
  168. th.principal_version = th.Internal._serialized_principal_version;
  169. } else if (type == 1) {
  170. BinaryReader reader = new BinaryReader (ms);
  171. string name = reader.ReadString ();
  172. string auth_type = reader.ReadString ();
  173. int n_roles = reader.ReadInt32 ();
  174. string [] roles = null;
  175. if (n_roles >= 0) {
  176. roles = new string [n_roles];
  177. for (int i = 0; i < n_roles; i++)
  178. roles [i] = reader.ReadString ();
  179. }
  180. th.principal = new GenericPrincipal (new GenericIdentity (name, auth_type), roles);
  181. } else if (type == 2 || type == 3) {
  182. string [] roles = type == 2 ? null : new string [0];
  183. th.principal = new GenericPrincipal (new GenericIdentity ("", ""), roles);
  184. }
  185. }
  186. static void SerializePrincipal (Thread th, IPrincipal value)
  187. {
  188. MemoryStream ms = new MemoryStream ();
  189. bool done = false;
  190. if (value.GetType () == typeof (GenericPrincipal)) {
  191. GenericPrincipal gp = (GenericPrincipal) value;
  192. if (gp.Identity != null && gp.Identity.GetType () == typeof (GenericIdentity)) {
  193. GenericIdentity id = (GenericIdentity) gp.Identity;
  194. if (id.Name == "" && id.AuthenticationType == "") {
  195. if (gp.Roles == null) {
  196. ms.WriteByte (2);
  197. done = true;
  198. } else if (gp.Roles.Length == 0) {
  199. ms.WriteByte (3);
  200. done = true;
  201. }
  202. } else {
  203. ms.WriteByte (1);
  204. BinaryWriter br = new BinaryWriter (ms);
  205. br.Write (gp.Identity.Name);
  206. br.Write (gp.Identity.AuthenticationType);
  207. string [] roles = gp.Roles;
  208. if (roles == null) {
  209. br.Write ((int) (-1));
  210. } else {
  211. br.Write (roles.Length);
  212. foreach (string s in roles) {
  213. br.Write (s);
  214. }
  215. }
  216. br.Flush ();
  217. done = true;
  218. }
  219. }
  220. }
  221. if (!done) {
  222. ms.WriteByte (0);
  223. BinaryFormatter bf = new BinaryFormatter ();
  224. try {
  225. bf.Serialize (ms, value);
  226. } catch {}
  227. }
  228. th.Internal._serialized_principal = ByteArrayToRootDomain (ms.ToArray ());
  229. }
  230. public static IPrincipal CurrentPrincipal {
  231. get {
  232. Thread th = CurrentThread;
  233. if (th.principal_version != th.Internal._serialized_principal_version)
  234. th.principal = null;
  235. if (th.principal != null)
  236. return th.principal;
  237. if (th.Internal._serialized_principal != null) {
  238. try {
  239. DeserializePrincipal (th);
  240. return th.principal;
  241. } catch {}
  242. }
  243. th.principal = GetDomain ().DefaultPrincipal;
  244. th.principal_version = th.Internal._serialized_principal_version;
  245. return th.principal;
  246. }
  247. [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
  248. set {
  249. Thread th = CurrentThread;
  250. if (value != GetDomain ().DefaultPrincipal) {
  251. ++th.Internal._serialized_principal_version;
  252. try {
  253. SerializePrincipal (th, value);
  254. } catch (Exception) {
  255. th.Internal._serialized_principal = null;
  256. }
  257. th.principal_version = th.Internal._serialized_principal_version;
  258. } else {
  259. th.Internal._serialized_principal = null;
  260. }
  261. th.principal = value;
  262. }
  263. }
  264. // Looks up the object associated with the current thread
  265. // this is called by the JIT directly, too
  266. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  267. private extern static InternalThread CurrentInternalThread_internal();
  268. public static Thread CurrentThread {
  269. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  270. get {
  271. if (current_thread == null)
  272. current_thread = new Thread (CurrentInternalThread_internal ());
  273. return current_thread;
  274. }
  275. }
  276. internal static int CurrentThreadId {
  277. get {
  278. return (int)(CurrentThread.internal_thread.thread_id);
  279. }
  280. }
  281. public static AppDomain GetDomain() {
  282. return AppDomain.CurrentDomain;
  283. }
  284. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  285. public extern static int GetDomainID();
  286. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  287. private extern static void ResetAbort_internal();
  288. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  289. public static void ResetAbort ()
  290. {
  291. ResetAbort_internal ();
  292. }
  293. [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
  294. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  295. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  296. public extern static bool Yield ();
  297. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  298. private extern static void Sleep_internal(int ms);
  299. public static void Sleep (int millisecondsTimeout)
  300. {
  301. if (millisecondsTimeout < Timeout.Infinite)
  302. throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
  303. Sleep_internal (millisecondsTimeout);
  304. }
  305. public static void Sleep (TimeSpan timeout)
  306. {
  307. long ms = (long) timeout.TotalMilliseconds;
  308. if (ms < Timeout.Infinite || ms > Int32.MaxValue)
  309. throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
  310. Sleep_internal ((int) ms);
  311. }
  312. // Returns the system thread handle
  313. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  314. private extern IntPtr Thread_internal (MulticastDelegate start);
  315. public Thread(ThreadStart start) {
  316. if(start==null) {
  317. throw new ArgumentNullException("Null ThreadStart");
  318. }
  319. m_Delegate=start;
  320. }
  321. private Thread (InternalThread it) {
  322. internal_thread = it;
  323. }
  324. // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
  325. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  326. ~Thread ()
  327. {
  328. }
  329. [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
  330. public ApartmentState ApartmentState {
  331. get {
  332. if ((ThreadState & ThreadState.Stopped) != 0)
  333. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  334. return (ApartmentState)Internal.apartment_state;
  335. }
  336. set {
  337. TrySetApartmentState (value);
  338. }
  339. }
  340. //[MethodImplAttribute (MethodImplOptions.InternalCall)]
  341. //private static extern int current_lcid ();
  342. public CultureInfo CurrentCulture {
  343. get {
  344. CultureInfo culture = current_culture;
  345. if (current_culture_set && culture != null)
  346. return culture;
  347. if (default_culture != null)
  348. return default_culture;
  349. current_culture = culture = CultureInfo.ConstructCurrentCulture ();
  350. return culture;
  351. }
  352. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  353. set {
  354. if (value == null)
  355. throw new ArgumentNullException ("value");
  356. value.CheckNeutral ();
  357. current_culture = value;
  358. current_culture_set = true;
  359. }
  360. }
  361. public CultureInfo CurrentUICulture {
  362. get {
  363. CultureInfo culture = current_ui_culture;
  364. if (current_ui_culture_set && culture != null)
  365. return culture;
  366. if (default_ui_culture != null)
  367. return default_ui_culture;
  368. current_ui_culture = culture = CultureInfo.ConstructCurrentUICulture ();
  369. return culture;
  370. }
  371. set {
  372. if (value == null)
  373. throw new ArgumentNullException ("value");
  374. current_ui_culture = value;
  375. current_ui_culture_set = true;
  376. }
  377. }
  378. public bool IsThreadPoolThread {
  379. get {
  380. return IsThreadPoolThreadInternal;
  381. }
  382. }
  383. internal bool IsThreadPoolThreadInternal {
  384. get {
  385. return Internal.threadpool_thread;
  386. }
  387. set {
  388. Internal.threadpool_thread = value;
  389. }
  390. }
  391. public bool IsAlive {
  392. get {
  393. ThreadState curstate = GetState (Internal);
  394. if((curstate & ThreadState.Aborted) != 0 ||
  395. (curstate & ThreadState.Stopped) != 0 ||
  396. (curstate & ThreadState.Unstarted) != 0) {
  397. return(false);
  398. } else {
  399. return(true);
  400. }
  401. }
  402. }
  403. public bool IsBackground {
  404. get {
  405. ThreadState thread_state = GetState (Internal);
  406. if ((thread_state & ThreadState.Stopped) != 0)
  407. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  408. return (thread_state & ThreadState.Background) != 0;
  409. }
  410. set {
  411. if (value) {
  412. SetState (Internal, ThreadState.Background);
  413. } else {
  414. ClrState (Internal, ThreadState.Background);
  415. }
  416. }
  417. }
  418. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  419. private extern static string GetName_internal (InternalThread thread);
  420. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  421. private extern static void SetName_internal (InternalThread thread, String name);
  422. /*
  423. * The thread name must be shared by appdomains, so it is stored in
  424. * unmanaged code.
  425. */
  426. public string Name {
  427. get {
  428. return GetName_internal (Internal);
  429. }
  430. set {
  431. SetName_internal (Internal, value);
  432. }
  433. }
  434. public ThreadPriority Priority {
  435. get {
  436. return (ThreadPriority)GetPriority (Internal);
  437. }
  438. set {
  439. // FIXME: This doesn't do anything yet
  440. SetPriority (Internal, (int)value);
  441. }
  442. }
  443. public ThreadState ThreadState {
  444. get {
  445. return GetState (Internal);
  446. }
  447. }
  448. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  449. private extern static void Abort_internal (InternalThread thread, object stateInfo);
  450. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  451. private extern static int GetPriority (InternalThread thread);
  452. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  453. private extern static void SetPriority (InternalThread thread, int priority);
  454. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  455. public void Abort ()
  456. {
  457. Abort_internal (Internal, null);
  458. }
  459. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  460. public void Abort (object stateInfo)
  461. {
  462. Abort_internal (Internal, stateInfo);
  463. }
  464. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  465. extern object GetAbortExceptionState ();
  466. internal object AbortReason {
  467. get {
  468. return GetAbortExceptionState ();
  469. }
  470. }
  471. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  472. private extern static void Interrupt_internal (InternalThread thread);
  473. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  474. public void Interrupt ()
  475. {
  476. Interrupt_internal (Internal);
  477. }
  478. // The current thread joins with 'this'. Set ms to 0 to block
  479. // until this actually exits.
  480. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  481. private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
  482. public void Join()
  483. {
  484. Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
  485. }
  486. public bool Join(int millisecondsTimeout)
  487. {
  488. if (millisecondsTimeout < Timeout.Infinite)
  489. throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
  490. return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
  491. }
  492. public bool Join(TimeSpan timeout)
  493. {
  494. long ms = (long) timeout.TotalMilliseconds;
  495. if (ms < Timeout.Infinite || ms > Int32.MaxValue)
  496. throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
  497. return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
  498. }
  499. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  500. public extern static void MemoryBarrier ();
  501. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  502. private extern void Resume_internal();
  503. [Obsolete ("")]
  504. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  505. public void Resume ()
  506. {
  507. Resume_internal ();
  508. }
  509. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  510. private extern static void SpinWait_nop ();
  511. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  512. public static void SpinWait (int iterations)
  513. {
  514. if (iterations < 0)
  515. return;
  516. while (iterations-- > 0)
  517. {
  518. SpinWait_nop ();
  519. }
  520. }
  521. static internal ContextCallback _ccb = new ContextCallback(ThreadStart_Context);
  522. static private void ThreadStart_Context(Object state)
  523. {
  524. var t = (Thread)state;
  525. if (t.m_Delegate is ThreadStart)
  526. {
  527. ((ThreadStart)t.m_Delegate)();
  528. }
  529. else
  530. {
  531. ((ParameterizedThreadStart)t.m_Delegate)(t.m_ThreadStartArg);
  532. }
  533. }
  534. private void StartInternal ()
  535. {
  536. current_thread = this;
  537. if (_ec != null) {
  538. ExecutionContext.Run (_ec, _ccb, (Object)this);
  539. return;
  540. }
  541. if (m_Delegate is ThreadStart) {
  542. ((ThreadStart) m_Delegate) ();
  543. } else {
  544. ((ParameterizedThreadStart) m_Delegate) (m_ThreadStartArg);
  545. }
  546. }
  547. public void Start() {
  548. StackCrawlMark stackMark = default (StackCrawlMark);
  549. // TODO: Use SetExecutionContextHelper to remove 2 of 3 levels of indirections
  550. ec_to_set = ExecutionContext.Capture (ref stackMark, ExecutionContext.CaptureOptions.IgnoreSyncCtx);
  551. Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
  552. // Thread_internal creates and starts the new thread,
  553. if (Thread_internal((ThreadStart) StartInternal) == (IntPtr) 0)
  554. throw new SystemException ("Thread creation failed.");
  555. }
  556. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  557. private extern static void Suspend_internal(InternalThread thread);
  558. [Obsolete ("")]
  559. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  560. public void Suspend ()
  561. {
  562. Suspend_internal (Internal);
  563. }
  564. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  565. extern private static void SetState (InternalThread thread, ThreadState set);
  566. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  567. extern private static void ClrState (InternalThread thread, ThreadState clr);
  568. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  569. extern private static ThreadState GetState (InternalThread thread);
  570. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  571. extern public static byte VolatileRead (ref byte address);
  572. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  573. extern public static double VolatileRead (ref double address);
  574. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  575. extern public static short VolatileRead (ref short address);
  576. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  577. extern public static int VolatileRead (ref int address);
  578. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  579. extern public static long VolatileRead (ref long address);
  580. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  581. extern public static IntPtr VolatileRead (ref IntPtr address);
  582. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  583. extern public static object VolatileRead (ref object address);
  584. [CLSCompliant(false)]
  585. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  586. extern public static sbyte VolatileRead (ref sbyte address);
  587. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  588. extern public static float VolatileRead (ref float address);
  589. [CLSCompliant (false)]
  590. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  591. extern public static ushort VolatileRead (ref ushort address);
  592. [CLSCompliant (false)]
  593. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  594. extern public static uint VolatileRead (ref uint address);
  595. [CLSCompliant (false)]
  596. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  597. extern public static ulong VolatileRead (ref ulong address);
  598. [CLSCompliant (false)]
  599. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  600. extern public static UIntPtr VolatileRead (ref UIntPtr address);
  601. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  602. extern public static void VolatileWrite (ref byte address, byte value);
  603. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  604. extern public static void VolatileWrite (ref double address, double value);
  605. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  606. extern public static void VolatileWrite (ref short address, short value);
  607. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  608. extern public static void VolatileWrite (ref int address, int value);
  609. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  610. extern public static void VolatileWrite (ref long address, long value);
  611. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  612. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  613. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  614. extern public static void VolatileWrite (ref object address, object value);
  615. [CLSCompliant(false)]
  616. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  617. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  618. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  619. extern public static void VolatileWrite (ref float address, float value);
  620. [CLSCompliant (false)]
  621. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  622. extern public static void VolatileWrite (ref ushort address, ushort value);
  623. [CLSCompliant (false)]
  624. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  625. extern public static void VolatileWrite (ref uint address, uint value);
  626. [CLSCompliant (false)]
  627. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  628. extern public static void VolatileWrite (ref ulong address, ulong value);
  629. [CLSCompliant (false)]
  630. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  631. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  632. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  633. extern static int SystemMaxStackStize ();
  634. static int GetProcessDefaultStackSize (int maxStackSize)
  635. {
  636. if (maxStackSize < 131072) // make sure stack is at least 128k big
  637. return 131072;
  638. int page_size = Environment.GetPageSize ();
  639. if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
  640. maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
  641. /* Respect the max stack size imposed by the system*/
  642. return Math.Min (maxStackSize, SystemMaxStackStize ());
  643. }
  644. void SetStart (MulticastDelegate start, int maxStackSize)
  645. {
  646. m_Delegate = start;
  647. Internal.stack_size = maxStackSize;
  648. }
  649. public int ManagedThreadId {
  650. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  651. get {
  652. return Internal.managed_id;
  653. }
  654. }
  655. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  656. public static void BeginCriticalRegion ()
  657. {
  658. CurrentThread.Internal.critical_region_level++;
  659. }
  660. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  661. public static void EndCriticalRegion ()
  662. {
  663. CurrentThread.Internal.critical_region_level--;
  664. }
  665. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  666. public static void BeginThreadAffinity ()
  667. {
  668. // Managed and native threads are currently bound together.
  669. }
  670. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  671. public static void EndThreadAffinity ()
  672. {
  673. // Managed and native threads are currently bound together.
  674. }
  675. public ApartmentState GetApartmentState ()
  676. {
  677. return (ApartmentState)Internal.apartment_state;
  678. }
  679. public void SetApartmentState (ApartmentState state)
  680. {
  681. if (!TrySetApartmentState (state))
  682. throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
  683. }
  684. public bool TrySetApartmentState (ApartmentState state)
  685. {
  686. if ((ThreadState & ThreadState.Unstarted) == 0)
  687. throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
  688. if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown &&
  689. (ApartmentState)Internal.apartment_state != state)
  690. return false;
  691. Internal.apartment_state = (byte)state;
  692. return true;
  693. }
  694. [ComVisible (false)]
  695. public override int GetHashCode ()
  696. {
  697. return ManagedThreadId;
  698. }
  699. public void Start (object parameter)
  700. {
  701. m_ThreadStartArg = parameter;
  702. Start ();
  703. }
  704. internal CultureInfo GetCurrentUICultureNoAppX ()
  705. {
  706. return CultureInfo.CurrentUICulture;
  707. }
  708. }
  709. }