Thread.cs 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  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;
  39. using System.Reflection;
  40. using System.Security;
  41. #if NET_2_0
  42. using System.Runtime.ConstrainedExecution;
  43. #endif
  44. namespace System.Threading {
  45. [ClassInterface (ClassInterfaceType.None)]
  46. #if NET_2_0
  47. [ComVisible (true)]
  48. [ComDefaultInterface (typeof (_Thread))]
  49. public sealed class Thread : CriticalFinalizerObject, _Thread {
  50. #else
  51. public sealed class Thread : _Thread {
  52. #endif
  53. #pragma warning disable 169, 414, 649
  54. #region Sync with metadata/object-internals.h
  55. int lock_thread_id;
  56. // stores a thread handle
  57. private IntPtr system_thread_handle;
  58. /* Note this is an opaque object (an array), not a CultureInfo */
  59. private object cached_culture_info;
  60. private IntPtr unused0;
  61. private bool threadpool_thread;
  62. /* accessed only from unmanaged code */
  63. private IntPtr name;
  64. private int name_len;
  65. private ThreadState state = ThreadState.Unstarted;
  66. private object abort_exc;
  67. private int abort_state_handle;
  68. /* thread_id is only accessed from unmanaged code */
  69. private Int64 thread_id;
  70. /* start_notify is used by the runtime to signal that Start()
  71. * is ok to return
  72. */
  73. private IntPtr start_notify;
  74. private IntPtr stack_ptr;
  75. private UIntPtr static_data; /* GC-tracked */
  76. private IntPtr jit_data;
  77. private IntPtr lock_data;
  78. Context current_appcontext;
  79. int stack_size;
  80. object start_obj;
  81. private IntPtr appdomain_refs;
  82. private int interruption_requested;
  83. private IntPtr suspend_event;
  84. private IntPtr suspended_event;
  85. private IntPtr resume_event;
  86. private IntPtr synch_cs;
  87. private IntPtr serialized_culture_info;
  88. private int serialized_culture_info_len;
  89. private IntPtr serialized_ui_culture_info;
  90. private int serialized_ui_culture_info_len;
  91. private bool thread_dump_requested;
  92. private IntPtr end_stack;
  93. private bool thread_interrupt_requested;
  94. private byte apartment_state = (byte)ApartmentState.Unknown;
  95. volatile int critical_region_level;
  96. private int small_id;
  97. private IntPtr manage_callback;
  98. private object pending_exception;
  99. /* This is the ExecutionContext that will be set by
  100. start_wrapper() in the runtime. */
  101. private ExecutionContext ec_to_set;
  102. private IntPtr interrupt_on_stop;
  103. /*
  104. * These fields are used to avoid having to increment corlib versions
  105. * when a new field is added to the unmanaged MonoThread structure.
  106. */
  107. private IntPtr unused3;
  108. private IntPtr unused4;
  109. private IntPtr unused5;
  110. private IntPtr unused6;
  111. #endregion
  112. #pragma warning restore 169, 414, 649
  113. // the name of local_slots is important as it's used by the runtime.
  114. [ThreadStatic]
  115. static object[] local_slots;
  116. /* The actual ExecutionContext of the thread. It's
  117. ThreadStatic so that it's not shared between
  118. AppDomains. */
  119. [ThreadStatic]
  120. static ExecutionContext _ec;
  121. // can be both a ThreadSart and a ParameterizedThreadStart
  122. private MulticastDelegate threadstart;
  123. //private string thread_name=null;
  124. #if NET_2_0
  125. private static int _managed_id_counter;
  126. private int managed_id;
  127. #endif
  128. private IPrincipal _principal;
  129. public static Context CurrentContext {
  130. [SecurityPermission (SecurityAction.LinkDemand, Infrastructure=true)]
  131. get {
  132. return(AppDomain.InternalGetContext ());
  133. }
  134. }
  135. #if !NET_2_1
  136. public static IPrincipal CurrentPrincipal {
  137. get {
  138. IPrincipal p = null;
  139. Thread th = CurrentThread;
  140. lock (th) {
  141. p = th._principal;
  142. if (p == null) {
  143. p = GetDomain ().DefaultPrincipal;
  144. th._principal = p;
  145. }
  146. }
  147. return p;
  148. }
  149. [SecurityPermission (SecurityAction.Demand, ControlPrincipal = true)]
  150. set {
  151. CurrentThread._principal = value;
  152. }
  153. }
  154. #endif
  155. // Looks up the object associated with the current thread
  156. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  157. private extern static Thread CurrentThread_internal();
  158. public static Thread CurrentThread {
  159. #if NET_2_0
  160. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  161. #endif
  162. get {
  163. return(CurrentThread_internal());
  164. }
  165. }
  166. internal static int CurrentThreadId {
  167. get {
  168. return (int)(CurrentThread.thread_id);
  169. }
  170. }
  171. // Stores a hash keyed by strings of LocalDataStoreSlot objects
  172. static Hashtable datastorehash;
  173. private static object datastore_lock = new object ();
  174. private static void InitDataStoreHash () {
  175. lock (datastore_lock) {
  176. if (datastorehash == null) {
  177. datastorehash = Hashtable.Synchronized(new Hashtable());
  178. }
  179. }
  180. }
  181. public static LocalDataStoreSlot AllocateNamedDataSlot (string name) {
  182. lock (datastore_lock) {
  183. if (datastorehash == null)
  184. InitDataStoreHash ();
  185. LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
  186. if (slot != null) {
  187. // This exception isnt documented (of
  188. // course) but .net throws it
  189. throw new ArgumentException("Named data slot already added");
  190. }
  191. slot = AllocateDataSlot ();
  192. datastorehash.Add (name, slot);
  193. return slot;
  194. }
  195. }
  196. public static void FreeNamedDataSlot (string name) {
  197. lock (datastore_lock) {
  198. if (datastorehash == null)
  199. InitDataStoreHash ();
  200. LocalDataStoreSlot slot = (LocalDataStoreSlot)datastorehash [name];
  201. if (slot != null) {
  202. datastorehash.Remove (slot);
  203. }
  204. }
  205. }
  206. public static LocalDataStoreSlot AllocateDataSlot () {
  207. return new LocalDataStoreSlot (true);
  208. }
  209. public static object GetData (LocalDataStoreSlot slot) {
  210. object[] slots = local_slots;
  211. if (slot == null)
  212. throw new ArgumentNullException ("slot");
  213. if (slots != null && slot.slot < slots.Length)
  214. return slots [slot.slot];
  215. return null;
  216. }
  217. public static void SetData (LocalDataStoreSlot slot, object data) {
  218. object[] slots = local_slots;
  219. if (slot == null)
  220. throw new ArgumentNullException ("slot");
  221. if (slots == null) {
  222. slots = new object [slot.slot + 2];
  223. local_slots = slots;
  224. } else if (slot.slot >= slots.Length) {
  225. object[] nslots = new object [slot.slot + 2];
  226. slots.CopyTo (nslots, 0);
  227. slots = nslots;
  228. local_slots = slots;
  229. }
  230. slots [slot.slot] = data;
  231. }
  232. public static AppDomain GetDomain() {
  233. return AppDomain.CurrentDomain;
  234. }
  235. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  236. public extern static int GetDomainID();
  237. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  238. internal extern static void FreeLocalSlotValues (int slot, bool thread_local);
  239. public static LocalDataStoreSlot GetNamedDataSlot(string name) {
  240. lock (datastore_lock) {
  241. if (datastorehash == null)
  242. InitDataStoreHash ();
  243. LocalDataStoreSlot slot=(LocalDataStoreSlot)datastorehash[name];
  244. if(slot==null) {
  245. slot=AllocateNamedDataSlot(name);
  246. }
  247. return(slot);
  248. }
  249. }
  250. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  251. private extern static void ResetAbort_internal();
  252. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  253. public static void ResetAbort ()
  254. {
  255. ResetAbort_internal ();
  256. }
  257. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  258. private extern static void Sleep_internal(int ms);
  259. public static void Sleep(int millisecondsTimeout) {
  260. if((millisecondsTimeout<0) && (millisecondsTimeout != Timeout.Infinite)) {
  261. throw new ArgumentException("Negative timeout");
  262. }
  263. Sleep_internal(millisecondsTimeout);
  264. }
  265. public static void Sleep(TimeSpan timeout) {
  266. // LAMESPEC: says to throw ArgumentException too
  267. int ms=Convert.ToInt32(timeout.TotalMilliseconds);
  268. if(ms < 0 || ms > Int32.MaxValue) {
  269. throw new ArgumentOutOfRangeException("Timeout out of range");
  270. }
  271. Sleep_internal(ms);
  272. }
  273. // Returns the system thread handle
  274. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  275. private extern IntPtr Thread_internal (MulticastDelegate start);
  276. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  277. private extern void Thread_init ();
  278. public Thread(ThreadStart start) {
  279. if(start==null) {
  280. throw new ArgumentNullException("Null ThreadStart");
  281. }
  282. threadstart=start;
  283. Thread_init ();
  284. }
  285. #if NET_2_0
  286. [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
  287. #endif
  288. public ApartmentState ApartmentState {
  289. get {
  290. if ((ThreadState & ThreadState.Stopped) != 0)
  291. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  292. return (ApartmentState)apartment_state;
  293. }
  294. set {
  295. #if NET_2_0
  296. TrySetApartmentState (value);
  297. #else
  298. /* Only throw this exception when
  299. * changing the state of another
  300. * thread. See bug 324338
  301. */
  302. if ((this != CurrentThread) &&
  303. (ThreadState & ThreadState.Unstarted) == 0)
  304. throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
  305. if (value != ApartmentState.STA && value != ApartmentState.MTA)
  306. throw new ArgumentOutOfRangeException ("value is not a valid apartment state.");
  307. if ((ApartmentState)apartment_state == ApartmentState.Unknown)
  308. apartment_state = (byte)value;
  309. #endif
  310. }
  311. }
  312. //[MethodImplAttribute (MethodImplOptions.InternalCall)]
  313. //private static extern int current_lcid ();
  314. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  315. private extern CultureInfo GetCachedCurrentCulture ();
  316. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  317. private extern byte[] GetSerializedCurrentCulture ();
  318. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  319. private extern void SetCachedCurrentCulture (CultureInfo culture);
  320. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  321. private extern void SetSerializedCurrentCulture (byte[] culture);
  322. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  323. private extern CultureInfo GetCachedCurrentUICulture ();
  324. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  325. private extern byte[] GetSerializedCurrentUICulture ();
  326. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  327. private extern void SetCachedCurrentUICulture (CultureInfo culture);
  328. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  329. private extern void SetSerializedCurrentUICulture (byte[] culture);
  330. /* If the current_lcid() isn't known by CultureInfo,
  331. * it will throw an exception which may cause
  332. * String.Concat to try and recursively look up the
  333. * CurrentCulture, which will throw an exception, etc.
  334. * Use a boolean to short-circuit this scenario.
  335. */
  336. private bool in_currentculture=false;
  337. static object culture_lock = new object ();
  338. /*
  339. * Thread objects are shared between appdomains, and CurrentCulture
  340. * should always return an object in the calling appdomain. See bug
  341. * http://bugzilla.ximian.com/show_bug.cgi?id=50049 for more info.
  342. * This is hard to implement correctly and efficiently, so the current
  343. * implementation is not perfect: changes made in one appdomain to the
  344. * state of the current cultureinfo object are not visible to other
  345. * appdomains.
  346. */
  347. public CultureInfo CurrentCulture {
  348. get {
  349. if (in_currentculture)
  350. /* Bail out */
  351. return CultureInfo.InvariantCulture;
  352. CultureInfo culture = GetCachedCurrentCulture ();
  353. if (culture != null)
  354. return culture;
  355. byte[] arr = GetSerializedCurrentCulture ();
  356. if (arr == null) {
  357. lock (culture_lock) {
  358. in_currentculture=true;
  359. culture = CultureInfo.ConstructCurrentCulture ();
  360. //
  361. // Don't serialize the culture in this case to avoid
  362. // initializing the serialization infrastructure in the
  363. // common case when the culture is not set explicitly.
  364. //
  365. SetCachedCurrentCulture (culture);
  366. in_currentculture = false;
  367. NumberFormatter.SetThreadCurrentCulture (culture);
  368. return culture;
  369. }
  370. }
  371. /*
  372. * No cultureinfo object exists for this domain, so create one
  373. * by deserializing the serialized form.
  374. */
  375. in_currentculture = true;
  376. try {
  377. BinaryFormatter bf = new BinaryFormatter ();
  378. MemoryStream ms = new MemoryStream (arr);
  379. culture = (CultureInfo)bf.Deserialize (ms);
  380. SetCachedCurrentCulture (culture);
  381. } finally {
  382. in_currentculture = false;
  383. }
  384. NumberFormatter.SetThreadCurrentCulture (culture);
  385. return culture;
  386. }
  387. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  388. set {
  389. if (value == null)
  390. throw new ArgumentNullException ("value");
  391. CultureInfo culture = GetCachedCurrentCulture ();
  392. if (culture == value)
  393. return;
  394. value.CheckNeutral ();
  395. in_currentculture = true;
  396. try {
  397. SetCachedCurrentCulture (value);
  398. byte[] serialized_form = null;
  399. if (value.IsReadOnly && value.cached_serialized_form != null) {
  400. serialized_form = value.cached_serialized_form;
  401. } else {
  402. BinaryFormatter bf = new BinaryFormatter();
  403. MemoryStream ms = new MemoryStream ();
  404. bf.Serialize (ms, value);
  405. serialized_form = ms.GetBuffer ();
  406. if (value.IsReadOnly)
  407. value.cached_serialized_form = serialized_form;
  408. }
  409. SetSerializedCurrentCulture (serialized_form);
  410. } finally {
  411. in_currentculture = false;
  412. }
  413. NumberFormatter.SetThreadCurrentCulture (value);
  414. }
  415. }
  416. public CultureInfo CurrentUICulture {
  417. get {
  418. if (in_currentculture)
  419. /* Bail out */
  420. return CultureInfo.InvariantCulture;
  421. CultureInfo culture = GetCachedCurrentUICulture ();
  422. if (culture != null)
  423. return culture;
  424. byte[] arr = GetSerializedCurrentUICulture ();
  425. if (arr == null) {
  426. lock (culture_lock) {
  427. in_currentculture=true;
  428. /* We don't
  429. * distinguish
  430. * between
  431. * System and
  432. * UI cultures
  433. */
  434. culture = CultureInfo.ConstructCurrentUICulture ();
  435. //
  436. // Don't serialize the culture in this case to avoid
  437. // initializing the serialization infrastructure in the
  438. // common case when the culture is not set explicitly.
  439. //
  440. SetCachedCurrentUICulture (culture);
  441. in_currentculture = false;
  442. return culture;
  443. }
  444. }
  445. /*
  446. * No cultureinfo object exists for this domain, so create one
  447. * by deserializing the serialized form.
  448. */
  449. in_currentculture = true;
  450. try {
  451. BinaryFormatter bf = new BinaryFormatter ();
  452. MemoryStream ms = new MemoryStream (arr);
  453. culture = (CultureInfo)bf.Deserialize (ms);
  454. SetCachedCurrentUICulture (culture);
  455. }
  456. finally {
  457. in_currentculture = false;
  458. }
  459. return culture;
  460. }
  461. set {
  462. in_currentculture = true;
  463. if (value == null)
  464. throw new ArgumentNullException ("value");
  465. CultureInfo culture = GetCachedCurrentUICulture ();
  466. if (culture == value)
  467. return;
  468. try {
  469. SetCachedCurrentUICulture (value);
  470. byte[] serialized_form = null;
  471. if (value.IsReadOnly && value.cached_serialized_form != null) {
  472. serialized_form = value.cached_serialized_form;
  473. } else {
  474. BinaryFormatter bf = new BinaryFormatter();
  475. MemoryStream ms = new MemoryStream ();
  476. bf.Serialize (ms, value);
  477. serialized_form = ms.GetBuffer ();
  478. if (value.IsReadOnly)
  479. value.cached_serialized_form = serialized_form;
  480. }
  481. SetSerializedCurrentUICulture (serialized_form);
  482. } finally {
  483. in_currentculture = false;
  484. }
  485. }
  486. }
  487. public bool IsThreadPoolThread {
  488. get {
  489. return IsThreadPoolThreadInternal;
  490. }
  491. }
  492. internal bool IsThreadPoolThreadInternal {
  493. get {
  494. return threadpool_thread;
  495. }
  496. set {
  497. threadpool_thread = value;
  498. }
  499. }
  500. public bool IsAlive {
  501. get {
  502. ThreadState curstate = GetState ();
  503. if((curstate & ThreadState.Aborted) != 0 ||
  504. (curstate & ThreadState.Stopped) != 0 ||
  505. (curstate & ThreadState.Unstarted) != 0) {
  506. return(false);
  507. } else {
  508. return(true);
  509. }
  510. }
  511. }
  512. public bool IsBackground {
  513. get {
  514. ThreadState thread_state = GetState ();
  515. if ((thread_state & ThreadState.Stopped) != 0)
  516. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  517. return (thread_state & ThreadState.Background) != 0;
  518. }
  519. set {
  520. if (value) {
  521. SetState (ThreadState.Background);
  522. } else {
  523. ClrState (ThreadState.Background);
  524. }
  525. }
  526. }
  527. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  528. private extern string GetName_internal ();
  529. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  530. private extern void SetName_internal (String name);
  531. /*
  532. * The thread name must be shared by appdomains, so it is stored in
  533. * unmanaged code.
  534. */
  535. public string Name {
  536. get {
  537. return GetName_internal ();
  538. }
  539. set {
  540. SetName_internal (value);
  541. }
  542. }
  543. public ThreadPriority Priority {
  544. get {
  545. return(ThreadPriority.Lowest);
  546. }
  547. set {
  548. // FIXME: Implement setter.
  549. }
  550. }
  551. public ThreadState ThreadState {
  552. get {
  553. return GetState ();
  554. }
  555. }
  556. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  557. private extern void Abort_internal (object stateInfo);
  558. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  559. public void Abort ()
  560. {
  561. Abort_internal (null);
  562. }
  563. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  564. public void Abort (object stateInfo)
  565. {
  566. Abort_internal (stateInfo);
  567. }
  568. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  569. internal extern object GetAbortExceptionState ();
  570. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  571. private extern void Interrupt_internal ();
  572. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  573. public void Interrupt ()
  574. {
  575. Interrupt_internal ();
  576. }
  577. // The current thread joins with 'this'. Set ms to 0 to block
  578. // until this actually exits.
  579. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  580. private extern bool Join_internal(int ms, IntPtr handle);
  581. public void Join()
  582. {
  583. Join_internal(Timeout.Infinite, system_thread_handle);
  584. }
  585. public bool Join(int millisecondsTimeout)
  586. {
  587. if (millisecondsTimeout != Timeout.Infinite && millisecondsTimeout < 0)
  588. throw new ArgumentException ("Timeout less than zero", "millisecondsTimeout");
  589. return Join_internal(millisecondsTimeout, system_thread_handle);
  590. }
  591. public bool Join(TimeSpan timeout)
  592. {
  593. // LAMESPEC: says to throw ArgumentException too
  594. int ms=Convert.ToInt32(timeout.TotalMilliseconds);
  595. if(ms < 0 || ms > Int32.MaxValue) {
  596. throw new ArgumentOutOfRangeException("timeout out of range");
  597. }
  598. return Join_internal(ms, system_thread_handle);
  599. }
  600. #if NET_1_1
  601. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  602. public extern static void MemoryBarrier ();
  603. #endif
  604. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  605. private extern void Resume_internal();
  606. #if NET_2_0
  607. [Obsolete ("")]
  608. #endif
  609. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  610. public void Resume ()
  611. {
  612. Resume_internal ();
  613. }
  614. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  615. private extern static void SpinWait_nop ();
  616. #if NET_2_0
  617. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  618. #endif
  619. public static void SpinWait (int iterations)
  620. {
  621. if (iterations < 0)
  622. return;
  623. while (iterations-- > 0)
  624. {
  625. SpinWait_nop ();
  626. }
  627. }
  628. #if NET_2_1 && !MONOTOUCH
  629. private void StartSafe ()
  630. {
  631. try {
  632. if (threadstart is ThreadStart) {
  633. ((ThreadStart) threadstart) ();
  634. } else {
  635. ((ParameterizedThreadStart) threadstart) (start_obj);
  636. }
  637. } catch (Exception ex) {
  638. MoonlightUnhandledException (ex);
  639. }
  640. }
  641. static MethodInfo moonlight_unhandled_exception = null;
  642. static internal void MoonlightUnhandledException (Exception e)
  643. {
  644. try {
  645. if (moonlight_unhandled_exception == null) {
  646. var assembly = System.Reflection.Assembly.Load ("System.Windows, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e");
  647. var application = assembly.GetType ("System.Windows.Application");
  648. moonlight_unhandled_exception = application.GetMethod ("OnUnhandledException",
  649. System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
  650. }
  651. moonlight_unhandled_exception.Invoke (null, new object [] { null, e });
  652. }
  653. catch {
  654. try {
  655. Console.WriteLine ("Unexpected exception while trying to report unhandled application exception: {0}", e);
  656. } catch {
  657. }
  658. }
  659. }
  660. #endif
  661. public void Start() {
  662. // propagate informations from the original thread to the new thread
  663. #if NET_2_0
  664. if (!ExecutionContext.IsFlowSuppressed ())
  665. ec_to_set = ExecutionContext.Capture ();
  666. #else
  667. // before 2.0 this was only used for security (mostly CAS) so we
  668. // do this only if the security manager is active
  669. if (SecurityManager.SecurityEnabled)
  670. ec_to_set = ExecutionContext.Capture ();
  671. #endif
  672. if (CurrentThread._principal != null)
  673. _principal = CurrentThread._principal;
  674. // Thread_internal creates and starts the new thread,
  675. #if NET_2_1 && !MONOTOUCH
  676. if (Thread_internal((ThreadStart) StartSafe) == (IntPtr) 0)
  677. #else
  678. if (Thread_internal(threadstart) == (IntPtr) 0)
  679. #endif
  680. throw new SystemException ("Thread creation failed.");
  681. }
  682. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  683. private extern void Suspend_internal();
  684. #if NET_2_0
  685. [Obsolete ("")]
  686. #endif
  687. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  688. public void Suspend ()
  689. {
  690. Suspend_internal ();
  691. }
  692. // Closes the system thread handle
  693. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  694. private extern void Thread_free_internal(IntPtr handle);
  695. #if NET_2_0
  696. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  697. #endif
  698. ~Thread() {
  699. Thread_free_internal(system_thread_handle);
  700. }
  701. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  702. extern private void SetState (ThreadState set);
  703. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  704. extern private void ClrState (ThreadState clr);
  705. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  706. extern private ThreadState GetState ();
  707. #if NET_1_1
  708. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  709. extern public static byte VolatileRead (ref byte address);
  710. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  711. extern public static double VolatileRead (ref double address);
  712. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  713. extern public static short VolatileRead (ref short address);
  714. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  715. extern public static int VolatileRead (ref int address);
  716. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  717. extern public static long VolatileRead (ref long address);
  718. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  719. extern public static IntPtr VolatileRead (ref IntPtr address);
  720. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  721. extern public static object VolatileRead (ref object address);
  722. [CLSCompliant(false)]
  723. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  724. extern public static sbyte VolatileRead (ref sbyte address);
  725. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  726. extern public static float VolatileRead (ref float address);
  727. [CLSCompliant (false)]
  728. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  729. extern public static ushort VolatileRead (ref ushort address);
  730. [CLSCompliant (false)]
  731. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  732. extern public static uint VolatileRead (ref uint address);
  733. [CLSCompliant (false)]
  734. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  735. extern public static ulong VolatileRead (ref ulong address);
  736. [CLSCompliant (false)]
  737. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  738. extern public static UIntPtr VolatileRead (ref UIntPtr address);
  739. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  740. extern public static void VolatileWrite (ref byte address, byte value);
  741. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  742. extern public static void VolatileWrite (ref double address, double value);
  743. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  744. extern public static void VolatileWrite (ref short address, short value);
  745. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  746. extern public static void VolatileWrite (ref int address, int value);
  747. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  748. extern public static void VolatileWrite (ref long address, long value);
  749. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  750. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  751. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  752. extern public static void VolatileWrite (ref object address, object value);
  753. [CLSCompliant(false)]
  754. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  755. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  756. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  757. extern public static void VolatileWrite (ref float address, float value);
  758. [CLSCompliant (false)]
  759. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  760. extern public static void VolatileWrite (ref ushort address, ushort value);
  761. [CLSCompliant (false)]
  762. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  763. extern public static void VolatileWrite (ref uint address, uint value);
  764. [CLSCompliant (false)]
  765. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  766. extern public static void VolatileWrite (ref ulong address, ulong value);
  767. [CLSCompliant (false)]
  768. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  769. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  770. #endif
  771. #if NET_2_0
  772. private static int GetNewManagedId() {
  773. return Interlocked.Increment(ref _managed_id_counter);
  774. }
  775. public Thread (ThreadStart start, int maxStackSize)
  776. {
  777. if (start == null)
  778. throw new ArgumentNullException ("start");
  779. if (maxStackSize < 131072)
  780. throw new ArgumentException ("< 128 kb", "maxStackSize");
  781. threadstart = start;
  782. stack_size = maxStackSize;
  783. Thread_init ();
  784. }
  785. public Thread (ParameterizedThreadStart start)
  786. {
  787. if (start == null)
  788. throw new ArgumentNullException ("start");
  789. threadstart = start;
  790. Thread_init ();
  791. }
  792. public Thread (ParameterizedThreadStart start, int maxStackSize)
  793. {
  794. if (start == null)
  795. throw new ArgumentNullException ("start");
  796. if (maxStackSize < 131072)
  797. throw new ArgumentException ("< 128 kb", "maxStackSize");
  798. threadstart = start;
  799. stack_size = maxStackSize;
  800. Thread_init ();
  801. }
  802. [MonoTODO ("limited to CompressedStack support")]
  803. public ExecutionContext ExecutionContext {
  804. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  805. get {
  806. if (_ec == null)
  807. _ec = new ExecutionContext ();
  808. return _ec;
  809. }
  810. }
  811. public int ManagedThreadId {
  812. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  813. get {
  814. if (managed_id == 0) {
  815. int new_managed_id = GetNewManagedId ();
  816. Interlocked.CompareExchange (ref managed_id, new_managed_id, 0);
  817. }
  818. return managed_id;
  819. }
  820. }
  821. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  822. public static void BeginCriticalRegion ()
  823. {
  824. CurrentThread.critical_region_level++;
  825. }
  826. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  827. public static void EndCriticalRegion ()
  828. {
  829. CurrentThread.critical_region_level--;
  830. }
  831. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  832. public static void BeginThreadAffinity ()
  833. {
  834. // Managed and native threads are currently bound together.
  835. }
  836. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  837. public static void EndThreadAffinity ()
  838. {
  839. // Managed and native threads are currently bound together.
  840. }
  841. public ApartmentState GetApartmentState ()
  842. {
  843. return (ApartmentState)apartment_state;
  844. }
  845. public void SetApartmentState (ApartmentState state)
  846. {
  847. if (!TrySetApartmentState (state))
  848. throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
  849. }
  850. public bool TrySetApartmentState (ApartmentState state)
  851. {
  852. /* Only throw this exception when changing the
  853. * state of another thread. See bug 324338
  854. */
  855. if ((this != CurrentThread) &&
  856. (ThreadState & ThreadState.Unstarted) == 0)
  857. throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
  858. if ((ApartmentState)apartment_state != ApartmentState.Unknown)
  859. return false;
  860. apartment_state = (byte)state;
  861. return true;
  862. }
  863. [ComVisible (false)]
  864. public override int GetHashCode ()
  865. {
  866. return ManagedThreadId;
  867. }
  868. public void Start (object parameter)
  869. {
  870. start_obj = parameter;
  871. Start ();
  872. }
  873. #else
  874. internal ExecutionContext ExecutionContext {
  875. get {
  876. if (_ec == null)
  877. _ec = new ExecutionContext ();
  878. return _ec;
  879. }
  880. }
  881. #endif
  882. #if !NET_2_1
  883. // NOTE: This method doesn't show in the class library status page because
  884. // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
  885. // But it's there!
  886. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  887. [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
  888. #if NET_2_0
  889. [Obsolete ("see CompressedStack class")]
  890. #endif
  891. #if NET_1_1
  892. public
  893. #else
  894. internal
  895. #endif
  896. CompressedStack GetCompressedStack ()
  897. {
  898. // Note: returns null if no CompressedStack has been set.
  899. // However CompressedStack.GetCompressedStack returns an
  900. // (empty?) CompressedStack instance.
  901. CompressedStack cs = ExecutionContext.SecurityContext.CompressedStack;
  902. return ((cs == null) || cs.IsEmpty ()) ? null : cs.CreateCopy ();
  903. }
  904. // NOTE: This method doesn't show in the class library status page because
  905. // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
  906. // But it's there!
  907. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  908. [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
  909. #if NET_2_0
  910. [Obsolete ("see CompressedStack class")]
  911. #endif
  912. #if NET_1_1
  913. public
  914. #else
  915. internal
  916. #endif
  917. void SetCompressedStack (CompressedStack stack)
  918. {
  919. ExecutionContext.SecurityContext.CompressedStack = stack;
  920. }
  921. #endif
  922. #if NET_1_1
  923. void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  924. {
  925. throw new NotImplementedException ();
  926. }
  927. void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  928. {
  929. throw new NotImplementedException ();
  930. }
  931. void _Thread.GetTypeInfoCount (out uint pcTInfo)
  932. {
  933. throw new NotImplementedException ();
  934. }
  935. void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
  936. IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  937. {
  938. throw new NotImplementedException ();
  939. }
  940. #endif
  941. }
  942. }