Thread.cs 25 KB

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