Thread.cs 28 KB

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