Thread.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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. public static Thread CurrentThread {
  270. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  271. get {
  272. if (current_thread == null)
  273. current_thread = new Thread (CurrentInternalThread_internal ());
  274. return current_thread;
  275. }
  276. }
  277. internal static int CurrentThreadId {
  278. get {
  279. return (int)(CurrentThread.internal_thread.thread_id);
  280. }
  281. }
  282. public static AppDomain GetDomain() {
  283. return AppDomain.CurrentDomain;
  284. }
  285. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  286. public extern static int GetDomainID();
  287. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  288. private extern static void ResetAbort_internal();
  289. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  290. public static void ResetAbort ()
  291. {
  292. ResetAbort_internal ();
  293. }
  294. [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
  295. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  296. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  297. public extern static bool Yield ();
  298. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  299. private extern static void Sleep_internal(int ms);
  300. public static void Sleep (int millisecondsTimeout)
  301. {
  302. if (millisecondsTimeout < Timeout.Infinite)
  303. throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
  304. Sleep_internal (millisecondsTimeout);
  305. }
  306. public static void Sleep (TimeSpan timeout)
  307. {
  308. long ms = (long) timeout.TotalMilliseconds;
  309. if (ms < Timeout.Infinite || ms > Int32.MaxValue)
  310. throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
  311. Sleep_internal ((int) ms);
  312. }
  313. // Returns the system thread handle
  314. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  315. private extern IntPtr Thread_internal (MulticastDelegate start);
  316. public Thread(ThreadStart start) {
  317. if(start==null) {
  318. throw new ArgumentNullException("Null ThreadStart");
  319. }
  320. m_Delegate=start;
  321. }
  322. private Thread (InternalThread it) {
  323. internal_thread = it;
  324. }
  325. // part of ".NETPortable,Version=v4.0,Profile=Profile3" i.e. FX4 and SL4
  326. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  327. ~Thread ()
  328. {
  329. }
  330. [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
  331. public ApartmentState ApartmentState {
  332. get {
  333. if ((ThreadState & ThreadState.Stopped) != 0)
  334. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  335. return (ApartmentState)Internal.apartment_state;
  336. }
  337. set {
  338. TrySetApartmentState (value);
  339. }
  340. }
  341. //[MethodImplAttribute (MethodImplOptions.InternalCall)]
  342. //private static extern int current_lcid ();
  343. public CultureInfo CurrentCulture {
  344. get {
  345. CultureInfo culture = current_culture;
  346. if (current_culture_set && culture != null)
  347. return culture;
  348. if (default_culture != null)
  349. return default_culture;
  350. current_culture = culture = CultureInfo.ConstructCurrentCulture ();
  351. return culture;
  352. }
  353. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  354. set {
  355. if (value == null)
  356. throw new ArgumentNullException ("value");
  357. value.CheckNeutral ();
  358. current_culture = value;
  359. current_culture_set = true;
  360. }
  361. }
  362. public CultureInfo CurrentUICulture {
  363. get {
  364. CultureInfo culture = current_ui_culture;
  365. if (current_ui_culture_set && culture != null)
  366. return culture;
  367. if (default_ui_culture != null)
  368. return default_ui_culture;
  369. current_ui_culture = culture = CultureInfo.ConstructCurrentUICulture ();
  370. return culture;
  371. }
  372. set {
  373. if (value == null)
  374. throw new ArgumentNullException ("value");
  375. current_ui_culture = value;
  376. current_ui_culture_set = true;
  377. }
  378. }
  379. public bool IsThreadPoolThread {
  380. get {
  381. return IsThreadPoolThreadInternal;
  382. }
  383. }
  384. internal bool IsThreadPoolThreadInternal {
  385. get {
  386. return Internal.threadpool_thread;
  387. }
  388. set {
  389. Internal.threadpool_thread = value;
  390. }
  391. }
  392. public bool IsAlive {
  393. get {
  394. ThreadState curstate = GetState (Internal);
  395. if((curstate & ThreadState.Aborted) != 0 ||
  396. (curstate & ThreadState.Stopped) != 0 ||
  397. (curstate & ThreadState.Unstarted) != 0) {
  398. return(false);
  399. } else {
  400. return(true);
  401. }
  402. }
  403. }
  404. public bool IsBackground {
  405. get {
  406. ThreadState thread_state = GetState (Internal);
  407. if ((thread_state & ThreadState.Stopped) != 0)
  408. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  409. return (thread_state & ThreadState.Background) != 0;
  410. }
  411. set {
  412. if (value) {
  413. SetState (Internal, ThreadState.Background);
  414. } else {
  415. ClrState (Internal, ThreadState.Background);
  416. }
  417. }
  418. }
  419. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  420. private extern static string GetName_internal (InternalThread thread);
  421. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  422. private extern static void SetName_internal (InternalThread thread, String name);
  423. /*
  424. * The thread name must be shared by appdomains, so it is stored in
  425. * unmanaged code.
  426. */
  427. public string Name {
  428. get {
  429. return GetName_internal (Internal);
  430. }
  431. set {
  432. SetName_internal (Internal, value);
  433. }
  434. }
  435. public ThreadPriority Priority {
  436. get {
  437. return (ThreadPriority)GetPriority (Internal);
  438. }
  439. set {
  440. // FIXME: This doesn't do anything yet
  441. SetPriority (Internal, (int)value);
  442. }
  443. }
  444. public ThreadState ThreadState {
  445. get {
  446. return GetState (Internal);
  447. }
  448. }
  449. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  450. private extern static void Abort_internal (InternalThread thread, object stateInfo);
  451. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  452. private extern static int GetPriority (InternalThread thread);
  453. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  454. private extern static void SetPriority (InternalThread thread, int priority);
  455. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  456. public void Abort ()
  457. {
  458. Abort_internal (Internal, null);
  459. }
  460. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  461. public void Abort (object stateInfo)
  462. {
  463. Abort_internal (Internal, stateInfo);
  464. }
  465. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  466. extern object GetAbortExceptionState ();
  467. internal object AbortReason {
  468. get {
  469. return GetAbortExceptionState ();
  470. }
  471. }
  472. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  473. private extern static void Interrupt_internal (InternalThread thread);
  474. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  475. public void Interrupt ()
  476. {
  477. Interrupt_internal (Internal);
  478. }
  479. // The current thread joins with 'this'. Set ms to 0 to block
  480. // until this actually exits.
  481. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  482. private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
  483. public void Join()
  484. {
  485. Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
  486. }
  487. public bool Join(int millisecondsTimeout)
  488. {
  489. if (millisecondsTimeout < Timeout.Infinite)
  490. throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
  491. return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
  492. }
  493. public bool Join(TimeSpan timeout)
  494. {
  495. long ms = (long) timeout.TotalMilliseconds;
  496. if (ms < Timeout.Infinite || ms > Int32.MaxValue)
  497. throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
  498. return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
  499. }
  500. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  501. public extern static void MemoryBarrier ();
  502. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  503. private extern void Resume_internal();
  504. [Obsolete ("")]
  505. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  506. public void Resume ()
  507. {
  508. Resume_internal ();
  509. }
  510. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  511. private extern static void SpinWait_nop ();
  512. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  513. public static void SpinWait (int iterations)
  514. {
  515. if (iterations < 0)
  516. return;
  517. while (iterations-- > 0)
  518. {
  519. SpinWait_nop ();
  520. }
  521. }
  522. private void StartInternal ()
  523. {
  524. current_thread = this;
  525. if (m_Delegate is ThreadStart) {
  526. ((ThreadStart) m_Delegate) ();
  527. } else {
  528. ((ParameterizedThreadStart) m_Delegate) (m_ThreadStartArg);
  529. }
  530. }
  531. public void Start() {
  532. // propagate informations from the original thread to the new thread
  533. ec_to_set = ExecutionContext.Capture (false, true);
  534. Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
  535. // Thread_internal creates and starts the new thread,
  536. if (Thread_internal((ThreadStart) StartInternal) == (IntPtr) 0)
  537. throw new SystemException ("Thread creation failed.");
  538. }
  539. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  540. private extern static void Suspend_internal(InternalThread thread);
  541. [Obsolete ("")]
  542. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  543. public void Suspend ()
  544. {
  545. Suspend_internal (Internal);
  546. }
  547. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  548. extern private static void SetState (InternalThread thread, ThreadState set);
  549. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  550. extern private static void ClrState (InternalThread thread, ThreadState clr);
  551. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  552. extern private static ThreadState GetState (InternalThread thread);
  553. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  554. extern public static byte VolatileRead (ref byte address);
  555. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  556. extern public static double VolatileRead (ref double address);
  557. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  558. extern public static short VolatileRead (ref short address);
  559. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  560. extern public static int VolatileRead (ref int address);
  561. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  562. extern public static long VolatileRead (ref long address);
  563. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  564. extern public static IntPtr VolatileRead (ref IntPtr address);
  565. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  566. extern public static object VolatileRead (ref object address);
  567. [CLSCompliant(false)]
  568. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  569. extern public static sbyte VolatileRead (ref sbyte address);
  570. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  571. extern public static float VolatileRead (ref float address);
  572. [CLSCompliant (false)]
  573. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  574. extern public static ushort VolatileRead (ref ushort address);
  575. [CLSCompliant (false)]
  576. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  577. extern public static uint VolatileRead (ref uint address);
  578. [CLSCompliant (false)]
  579. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  580. extern public static ulong VolatileRead (ref ulong address);
  581. [CLSCompliant (false)]
  582. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  583. extern public static UIntPtr VolatileRead (ref UIntPtr address);
  584. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  585. extern public static void VolatileWrite (ref byte address, byte value);
  586. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  587. extern public static void VolatileWrite (ref double address, double value);
  588. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  589. extern public static void VolatileWrite (ref short address, short value);
  590. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  591. extern public static void VolatileWrite (ref int address, int value);
  592. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  593. extern public static void VolatileWrite (ref long address, long value);
  594. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  595. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  596. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  597. extern public static void VolatileWrite (ref object address, object value);
  598. [CLSCompliant(false)]
  599. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  600. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  601. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  602. extern public static void VolatileWrite (ref float address, float value);
  603. [CLSCompliant (false)]
  604. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  605. extern public static void VolatileWrite (ref ushort address, ushort value);
  606. [CLSCompliant (false)]
  607. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  608. extern public static void VolatileWrite (ref uint address, uint value);
  609. [CLSCompliant (false)]
  610. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  611. extern public static void VolatileWrite (ref ulong address, ulong value);
  612. [CLSCompliant (false)]
  613. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  614. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  615. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  616. extern static int SystemMaxStackStize ();
  617. static int GetProcessDefaultStackSize (int maxStackSize)
  618. {
  619. if (maxStackSize < 131072) // make sure stack is at least 128k big
  620. return 131072;
  621. int page_size = Environment.GetPageSize ();
  622. if ((maxStackSize % page_size) != 0) // round up to a divisible of page size
  623. maxStackSize = (maxStackSize / (page_size - 1)) * page_size;
  624. /* Respect the max stack size imposed by the system*/
  625. return Math.Min (maxStackSize, SystemMaxStackStize ());
  626. }
  627. void SetStart (MulticastDelegate start, int maxStackSize)
  628. {
  629. m_Delegate = start;
  630. Internal.stack_size = maxStackSize;
  631. }
  632. public ExecutionContext ExecutionContext {
  633. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  634. get {
  635. if (_ec == null)
  636. _ec = new ExecutionContext ();
  637. return _ec;
  638. }
  639. internal set {
  640. _ec = value;
  641. }
  642. }
  643. internal bool HasExecutionContext {
  644. get {
  645. return _ec != null;
  646. }
  647. }
  648. public int ManagedThreadId {
  649. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  650. get {
  651. return Internal.managed_id;
  652. }
  653. }
  654. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  655. public static void BeginCriticalRegion ()
  656. {
  657. CurrentThread.Internal.critical_region_level++;
  658. }
  659. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  660. public static void EndCriticalRegion ()
  661. {
  662. CurrentThread.Internal.critical_region_level--;
  663. }
  664. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  665. public static void BeginThreadAffinity ()
  666. {
  667. // Managed and native threads are currently bound together.
  668. }
  669. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  670. public static void EndThreadAffinity ()
  671. {
  672. // Managed and native threads are currently bound together.
  673. }
  674. public ApartmentState GetApartmentState ()
  675. {
  676. return (ApartmentState)Internal.apartment_state;
  677. }
  678. public void SetApartmentState (ApartmentState state)
  679. {
  680. if (!TrySetApartmentState (state))
  681. throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
  682. }
  683. public bool TrySetApartmentState (ApartmentState state)
  684. {
  685. if ((ThreadState & ThreadState.Unstarted) == 0)
  686. throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
  687. if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown &&
  688. (ApartmentState)Internal.apartment_state != state)
  689. return false;
  690. Internal.apartment_state = (byte)state;
  691. return true;
  692. }
  693. [ComVisible (false)]
  694. public override int GetHashCode ()
  695. {
  696. return ManagedThreadId;
  697. }
  698. public void Start (object parameter)
  699. {
  700. m_ThreadStartArg = parameter;
  701. Start ();
  702. }
  703. internal CultureInfo GetCurrentUICultureNoAppX ()
  704. {
  705. return CultureInfo.CurrentUICulture;
  706. }
  707. }
  708. }