Thread.cs 34 KB

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