Thread.cs 26 KB

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