Thread.cs 34 KB

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