Thread.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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 !MOONLIGHT
  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 !MOONLIGHT
  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. #if NET_4_0 || BOOTSTRAP_NET_4_0
  318. [HostProtectionAttribute (SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
  319. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  320. public extern static bool Yield ();
  321. #endif
  322. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  323. private extern static void Sleep_internal(int ms);
  324. public static void Sleep (int millisecondsTimeout)
  325. {
  326. if (millisecondsTimeout < Timeout.Infinite)
  327. throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Negative timeout");
  328. Sleep_internal (millisecondsTimeout);
  329. }
  330. public static void Sleep (TimeSpan timeout)
  331. {
  332. long ms = (long) timeout.TotalMilliseconds;
  333. if (ms < Timeout.Infinite || ms > Int32.MaxValue)
  334. throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
  335. Sleep_internal ((int) ms);
  336. }
  337. // Returns the system thread handle
  338. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  339. private extern IntPtr Thread_internal (MulticastDelegate start);
  340. public Thread(ThreadStart start) {
  341. if(start==null) {
  342. throw new ArgumentNullException("Null ThreadStart");
  343. }
  344. threadstart=start;
  345. }
  346. private Thread (InternalThread it) {
  347. internal_thread = it;
  348. }
  349. #if !MOONLIGHT
  350. [Obsolete ("Deprecated in favor of GetApartmentState, SetApartmentState and TrySetApartmentState.")]
  351. public ApartmentState ApartmentState {
  352. get {
  353. if ((ThreadState & ThreadState.Stopped) != 0)
  354. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  355. return (ApartmentState)Internal.apartment_state;
  356. }
  357. set {
  358. TrySetApartmentState (value);
  359. }
  360. }
  361. #endif // !NET_2_1
  362. //[MethodImplAttribute (MethodImplOptions.InternalCall)]
  363. //private static extern int current_lcid ();
  364. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  365. private extern static CultureInfo GetCachedCurrentCulture (InternalThread thread);
  366. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  367. private extern void SetCachedCurrentCulture (CultureInfo culture);
  368. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  369. private extern static CultureInfo GetCachedCurrentUICulture (InternalThread thread);
  370. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  371. private extern void SetCachedCurrentUICulture (CultureInfo culture);
  372. /* FIXME: in_currentculture exists once, but
  373. culture_lock is once per appdomain. Is it correct
  374. to lock this way? */
  375. static object culture_lock = new object ();
  376. /*
  377. * Thread objects are shared between appdomains, and CurrentCulture
  378. * should always return an object in the calling appdomain. See bug
  379. * http://bugzilla.ximian.com/show_bug.cgi?id=50049 for more info.
  380. * This is hard to implement correctly and efficiently, so the current
  381. * implementation is not perfect: changes made in one appdomain to the
  382. * state of the current cultureinfo object are not visible to other
  383. * appdomains.
  384. */
  385. public CultureInfo CurrentCulture {
  386. get {
  387. if (Internal.in_currentculture)
  388. /* Bail out */
  389. return CultureInfo.InvariantCulture;
  390. CultureInfo culture = GetCachedCurrentCulture (Internal);
  391. if (culture != null)
  392. return culture;
  393. byte[] arr = ByteArrayToCurrentDomain (Internal.serialized_culture_info);
  394. if (arr == null) {
  395. lock (culture_lock) {
  396. Internal.in_currentculture=true;
  397. culture = CultureInfo.ConstructCurrentCulture ();
  398. //
  399. // Don't serialize the culture in this case to avoid
  400. // initializing the serialization infrastructure in the
  401. // common case when the culture is not set explicitly.
  402. //
  403. SetCachedCurrentCulture (culture);
  404. Internal.in_currentculture = false;
  405. NumberFormatter.SetThreadCurrentCulture (culture);
  406. return culture;
  407. }
  408. }
  409. /*
  410. * No cultureinfo object exists for this domain, so create one
  411. * by deserializing the serialized form.
  412. */
  413. Internal.in_currentculture = true;
  414. try {
  415. BinaryFormatter bf = new BinaryFormatter ();
  416. MemoryStream ms = new MemoryStream (arr);
  417. culture = (CultureInfo)bf.Deserialize (ms);
  418. SetCachedCurrentCulture (culture);
  419. } finally {
  420. Internal.in_currentculture = false;
  421. }
  422. NumberFormatter.SetThreadCurrentCulture (culture);
  423. return culture;
  424. }
  425. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  426. set {
  427. if (value == null)
  428. throw new ArgumentNullException ("value");
  429. CultureInfo culture = GetCachedCurrentCulture (Internal);
  430. if (culture == value)
  431. return;
  432. value.CheckNeutral ();
  433. Internal.in_currentculture = true;
  434. try {
  435. SetCachedCurrentCulture (value);
  436. byte[] serialized_form = null;
  437. if (value.IsReadOnly && value.cached_serialized_form != null) {
  438. serialized_form = value.cached_serialized_form;
  439. } else {
  440. BinaryFormatter bf = new BinaryFormatter();
  441. MemoryStream ms = new MemoryStream ();
  442. bf.Serialize (ms, value);
  443. serialized_form = ms.GetBuffer ();
  444. if (value.IsReadOnly)
  445. value.cached_serialized_form = serialized_form;
  446. }
  447. Internal.serialized_culture_info = ByteArrayToRootDomain (serialized_form);
  448. } finally {
  449. Internal.in_currentculture = false;
  450. }
  451. NumberFormatter.SetThreadCurrentCulture (value);
  452. }
  453. }
  454. public CultureInfo CurrentUICulture {
  455. get {
  456. if (Internal.in_currentculture)
  457. /* Bail out */
  458. return CultureInfo.InvariantCulture;
  459. CultureInfo culture = GetCachedCurrentUICulture (Internal);
  460. if (culture != null)
  461. return culture;
  462. byte[] arr = ByteArrayToCurrentDomain (Internal.serialized_ui_culture_info);
  463. if (arr == null) {
  464. lock (culture_lock) {
  465. Internal.in_currentculture=true;
  466. /* We don't
  467. * distinguish
  468. * between
  469. * System and
  470. * UI cultures
  471. */
  472. culture = CultureInfo.ConstructCurrentUICulture ();
  473. //
  474. // Don't serialize the culture in this case to avoid
  475. // initializing the serialization infrastructure in the
  476. // common case when the culture is not set explicitly.
  477. //
  478. SetCachedCurrentUICulture (culture);
  479. Internal.in_currentculture = false;
  480. return culture;
  481. }
  482. }
  483. /*
  484. * No cultureinfo object exists for this domain, so create one
  485. * by deserializing the serialized form.
  486. */
  487. Internal.in_currentculture = true;
  488. try {
  489. BinaryFormatter bf = new BinaryFormatter ();
  490. MemoryStream ms = new MemoryStream (arr);
  491. culture = (CultureInfo)bf.Deserialize (ms);
  492. SetCachedCurrentUICulture (culture);
  493. }
  494. finally {
  495. Internal.in_currentculture = false;
  496. }
  497. return culture;
  498. }
  499. set {
  500. if (value == null)
  501. throw new ArgumentNullException ("value");
  502. CultureInfo culture = GetCachedCurrentUICulture (Internal);
  503. if (culture == value)
  504. return;
  505. Internal.in_currentculture = true;
  506. try {
  507. SetCachedCurrentUICulture (value);
  508. byte[] serialized_form = null;
  509. if (value.IsReadOnly && value.cached_serialized_form != null) {
  510. serialized_form = value.cached_serialized_form;
  511. } else {
  512. BinaryFormatter bf = new BinaryFormatter();
  513. MemoryStream ms = new MemoryStream ();
  514. bf.Serialize (ms, value);
  515. serialized_form = ms.GetBuffer ();
  516. if (value.IsReadOnly)
  517. value.cached_serialized_form = serialized_form;
  518. }
  519. Internal.serialized_ui_culture_info = ByteArrayToRootDomain (serialized_form);
  520. } finally {
  521. Internal.in_currentculture = false;
  522. }
  523. }
  524. }
  525. public bool IsThreadPoolThread {
  526. get {
  527. return IsThreadPoolThreadInternal;
  528. }
  529. }
  530. internal bool IsThreadPoolThreadInternal {
  531. get {
  532. return Internal.threadpool_thread;
  533. }
  534. set {
  535. Internal.threadpool_thread = value;
  536. }
  537. }
  538. public bool IsAlive {
  539. get {
  540. ThreadState curstate = GetState (Internal);
  541. if((curstate & ThreadState.Aborted) != 0 ||
  542. (curstate & ThreadState.Stopped) != 0 ||
  543. (curstate & ThreadState.Unstarted) != 0) {
  544. return(false);
  545. } else {
  546. return(true);
  547. }
  548. }
  549. }
  550. public bool IsBackground {
  551. get {
  552. ThreadState thread_state = GetState (Internal);
  553. if ((thread_state & ThreadState.Stopped) != 0)
  554. throw new ThreadStateException ("Thread is dead; state can not be accessed.");
  555. return (thread_state & ThreadState.Background) != 0;
  556. }
  557. set {
  558. if (value) {
  559. SetState (Internal, ThreadState.Background);
  560. } else {
  561. ClrState (Internal, ThreadState.Background);
  562. }
  563. }
  564. }
  565. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  566. private extern static string GetName_internal (InternalThread thread);
  567. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  568. private extern static void SetName_internal (InternalThread thread, String name);
  569. /*
  570. * The thread name must be shared by appdomains, so it is stored in
  571. * unmanaged code.
  572. */
  573. public string Name {
  574. get {
  575. return GetName_internal (Internal);
  576. }
  577. set {
  578. SetName_internal (Internal, value);
  579. }
  580. }
  581. #if !MOONLIGHT
  582. public ThreadPriority Priority {
  583. get {
  584. return(ThreadPriority.Lowest);
  585. }
  586. set {
  587. // FIXME: Implement setter.
  588. }
  589. }
  590. #endif
  591. public ThreadState ThreadState {
  592. get {
  593. return GetState (Internal);
  594. }
  595. }
  596. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  597. private extern static void Abort_internal (InternalThread thread, object stateInfo);
  598. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  599. public void Abort ()
  600. {
  601. Abort_internal (Internal, null);
  602. }
  603. #if !MOONLIGHT
  604. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  605. public void Abort (object stateInfo)
  606. {
  607. Abort_internal (Internal, stateInfo);
  608. }
  609. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  610. internal extern object GetAbortExceptionState ();
  611. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  612. private extern static void Interrupt_internal (InternalThread thread);
  613. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  614. public void Interrupt ()
  615. {
  616. Interrupt_internal (Internal);
  617. }
  618. #endif
  619. // The current thread joins with 'this'. Set ms to 0 to block
  620. // until this actually exits.
  621. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  622. private extern static bool Join_internal(InternalThread thread, int ms, IntPtr handle);
  623. public void Join()
  624. {
  625. Join_internal(Internal, Timeout.Infinite, Internal.system_thread_handle);
  626. }
  627. public bool Join(int millisecondsTimeout)
  628. {
  629. if (millisecondsTimeout < Timeout.Infinite)
  630. throw new ArgumentOutOfRangeException ("millisecondsTimeout", "Timeout less than zero");
  631. return Join_internal (Internal, millisecondsTimeout, Internal.system_thread_handle);
  632. }
  633. #if !MOONLIGHT
  634. public bool Join(TimeSpan timeout)
  635. {
  636. long ms = (long) timeout.TotalMilliseconds;
  637. if (ms < Timeout.Infinite || ms > Int32.MaxValue)
  638. throw new ArgumentOutOfRangeException ("timeout", "timeout out of range");
  639. return Join_internal (Internal, (int) ms, Internal.system_thread_handle);
  640. }
  641. #endif
  642. #if NET_1_1
  643. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  644. public extern static void MemoryBarrier ();
  645. #endif
  646. #if !MOONLIGHT
  647. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  648. private extern void Resume_internal();
  649. [Obsolete ("")]
  650. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  651. public void Resume ()
  652. {
  653. Resume_internal ();
  654. }
  655. #endif // !NET_2_1
  656. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  657. private extern static void SpinWait_nop ();
  658. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  659. public static void SpinWait (int iterations)
  660. {
  661. if (iterations < 0)
  662. return;
  663. while (iterations-- > 0)
  664. {
  665. SpinWait_nop ();
  666. }
  667. }
  668. #if MOONLIGHT
  669. private void StartSafe ()
  670. {
  671. current_thread = this;
  672. try {
  673. if (threadstart is ThreadStart) {
  674. ((ThreadStart) threadstart) ();
  675. } else {
  676. ((ParameterizedThreadStart) threadstart) (start_obj);
  677. }
  678. } catch (ThreadAbortException) {
  679. // do nothing
  680. } catch (Exception ex) {
  681. MoonlightUnhandledException (ex);
  682. }
  683. }
  684. static MethodInfo moonlight_unhandled_exception = null;
  685. static internal void MoonlightUnhandledException (Exception e)
  686. {
  687. try {
  688. if (moonlight_unhandled_exception == null) {
  689. var assembly = System.Reflection.Assembly.Load ("System.Windows, Version=2.0.5.0, Culture=Neutral, PublicKeyToken=7cec85d7bea7798e");
  690. var application = assembly.GetType ("System.Windows.Application");
  691. moonlight_unhandled_exception = application.GetMethod ("OnUnhandledException",
  692. System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
  693. }
  694. moonlight_unhandled_exception.Invoke (null, new object [] { null, e });
  695. }
  696. catch {
  697. try {
  698. Console.WriteLine ("Unexpected exception while trying to report unhandled application exception: {0}", e);
  699. } catch {
  700. }
  701. }
  702. }
  703. #endif
  704. private void StartUnsafe ()
  705. {
  706. current_thread = this;
  707. if (threadstart is ThreadStart) {
  708. ((ThreadStart) threadstart) ();
  709. } else {
  710. ((ParameterizedThreadStart) threadstart) (start_obj);
  711. }
  712. }
  713. public void Start() {
  714. // propagate informations from the original thread to the new thread
  715. if (!ExecutionContext.IsFlowSuppressed ())
  716. ec_to_set = ExecutionContext.Capture ();
  717. Internal._serialized_principal = CurrentThread.Internal._serialized_principal;
  718. // Thread_internal creates and starts the new thread,
  719. #if MOONLIGHT
  720. if (Thread_internal((ThreadStart) StartSafe) == (IntPtr) 0)
  721. #else
  722. if (Thread_internal((ThreadStart) StartUnsafe) == (IntPtr) 0)
  723. #endif
  724. throw new SystemException ("Thread creation failed.");
  725. }
  726. #if !MOONLIGHT
  727. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  728. private extern static void Suspend_internal(InternalThread thread);
  729. [Obsolete ("")]
  730. [SecurityPermission (SecurityAction.Demand, ControlThread=true)]
  731. public void Suspend ()
  732. {
  733. Suspend_internal (Internal);
  734. }
  735. #endif // !NET_2_1
  736. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  737. extern private static void SetState (InternalThread thread, ThreadState set);
  738. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  739. extern private static void ClrState (InternalThread thread, ThreadState clr);
  740. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  741. extern private static ThreadState GetState (InternalThread thread);
  742. #if NET_1_1
  743. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  744. extern public static byte VolatileRead (ref byte address);
  745. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  746. extern public static double VolatileRead (ref double address);
  747. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  748. extern public static short VolatileRead (ref short address);
  749. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  750. extern public static int VolatileRead (ref int address);
  751. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  752. extern public static long VolatileRead (ref long address);
  753. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  754. extern public static IntPtr VolatileRead (ref IntPtr address);
  755. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  756. extern public static object VolatileRead (ref object address);
  757. [CLSCompliant(false)]
  758. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  759. extern public static sbyte VolatileRead (ref sbyte address);
  760. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  761. extern public static float VolatileRead (ref float address);
  762. [CLSCompliant (false)]
  763. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  764. extern public static ushort VolatileRead (ref ushort address);
  765. [CLSCompliant (false)]
  766. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  767. extern public static uint VolatileRead (ref uint address);
  768. [CLSCompliant (false)]
  769. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  770. extern public static ulong VolatileRead (ref ulong address);
  771. [CLSCompliant (false)]
  772. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  773. extern public static UIntPtr VolatileRead (ref UIntPtr address);
  774. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  775. extern public static void VolatileWrite (ref byte address, byte value);
  776. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  777. extern public static void VolatileWrite (ref double address, double value);
  778. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  779. extern public static void VolatileWrite (ref short address, short value);
  780. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  781. extern public static void VolatileWrite (ref int address, int value);
  782. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  783. extern public static void VolatileWrite (ref long address, long value);
  784. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  785. extern public static void VolatileWrite (ref IntPtr address, IntPtr value);
  786. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  787. extern public static void VolatileWrite (ref object address, object value);
  788. [CLSCompliant(false)]
  789. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  790. extern public static void VolatileWrite (ref sbyte address, sbyte value);
  791. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  792. extern public static void VolatileWrite (ref float address, float value);
  793. [CLSCompliant (false)]
  794. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  795. extern public static void VolatileWrite (ref ushort address, ushort value);
  796. [CLSCompliant (false)]
  797. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  798. extern public static void VolatileWrite (ref uint address, uint value);
  799. [CLSCompliant (false)]
  800. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  801. extern public static void VolatileWrite (ref ulong address, ulong value);
  802. [CLSCompliant (false)]
  803. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  804. extern public static void VolatileWrite (ref UIntPtr address, UIntPtr value);
  805. #endif
  806. private static int GetNewManagedId() {
  807. return Interlocked.Increment(ref _managed_id_counter);
  808. }
  809. public Thread (ThreadStart start, int maxStackSize)
  810. {
  811. if (start == null)
  812. throw new ArgumentNullException ("start");
  813. if (maxStackSize < 131072)
  814. throw new ArgumentException ("< 128 kb", "maxStackSize");
  815. threadstart = start;
  816. Internal.stack_size = maxStackSize;
  817. }
  818. public Thread (ParameterizedThreadStart start)
  819. {
  820. if (start == null)
  821. throw new ArgumentNullException ("start");
  822. threadstart = start;
  823. }
  824. public Thread (ParameterizedThreadStart start, int maxStackSize)
  825. {
  826. if (start == null)
  827. throw new ArgumentNullException ("start");
  828. if (maxStackSize < 131072)
  829. throw new ArgumentException ("< 128 kb", "maxStackSize");
  830. threadstart = start;
  831. Internal.stack_size = maxStackSize;
  832. }
  833. [MonoTODO ("limited to CompressedStack support")]
  834. public ExecutionContext ExecutionContext {
  835. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  836. get {
  837. if (_ec == null)
  838. _ec = new ExecutionContext ();
  839. return _ec;
  840. }
  841. }
  842. public int ManagedThreadId {
  843. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.Success)]
  844. get {
  845. if (Internal.managed_id == 0) {
  846. int new_managed_id = GetNewManagedId ();
  847. Interlocked.CompareExchange (ref Internal.managed_id, new_managed_id, 0);
  848. }
  849. return Internal.managed_id;
  850. }
  851. }
  852. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.MayFail)]
  853. public static void BeginCriticalRegion ()
  854. {
  855. CurrentThread.Internal.critical_region_level++;
  856. }
  857. [ReliabilityContract (Consistency.WillNotCorruptState, Cer.Success)]
  858. public static void EndCriticalRegion ()
  859. {
  860. CurrentThread.Internal.critical_region_level--;
  861. }
  862. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  863. public static void BeginThreadAffinity ()
  864. {
  865. // Managed and native threads are currently bound together.
  866. }
  867. [ReliabilityContractAttribute (Consistency.WillNotCorruptState, Cer.MayFail)]
  868. public static void EndThreadAffinity ()
  869. {
  870. // Managed and native threads are currently bound together.
  871. }
  872. #if !MOONLIGHT
  873. public ApartmentState GetApartmentState ()
  874. {
  875. return (ApartmentState)Internal.apartment_state;
  876. }
  877. public void SetApartmentState (ApartmentState state)
  878. {
  879. if (!TrySetApartmentState (state))
  880. throw new InvalidOperationException ("Failed to set the specified COM apartment state.");
  881. }
  882. public bool TrySetApartmentState (ApartmentState state)
  883. {
  884. /* Only throw this exception when changing the
  885. * state of another thread. See bug 324338
  886. */
  887. if ((this != CurrentThread) &&
  888. (ThreadState & ThreadState.Unstarted) == 0)
  889. throw new ThreadStateException ("Thread was in an invalid state for the operation being executed.");
  890. if ((ApartmentState)Internal.apartment_state != ApartmentState.Unknown)
  891. return false;
  892. Internal.apartment_state = (byte)state;
  893. return true;
  894. }
  895. #endif // !NET_2_1
  896. [ComVisible (false)]
  897. public override int GetHashCode ()
  898. {
  899. return ManagedThreadId;
  900. }
  901. public void Start (object parameter)
  902. {
  903. start_obj = parameter;
  904. Start ();
  905. }
  906. #if !MOONLIGHT
  907. // NOTE: This method doesn't show in the class library status page because
  908. // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
  909. // But it's there!
  910. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  911. [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
  912. [Obsolete ("see CompressedStack class")]
  913. #if NET_1_1
  914. public
  915. #else
  916. internal
  917. #endif
  918. CompressedStack GetCompressedStack ()
  919. {
  920. // Note: returns null if no CompressedStack has been set.
  921. // However CompressedStack.GetCompressedStack returns an
  922. // (empty?) CompressedStack instance.
  923. CompressedStack cs = ExecutionContext.SecurityContext.CompressedStack;
  924. return ((cs == null) || cs.IsEmpty ()) ? null : cs.CreateCopy ();
  925. }
  926. // NOTE: This method doesn't show in the class library status page because
  927. // it cannot be "found" with the StrongNameIdentityPermission for ECMA key.
  928. // But it's there!
  929. [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode = true)]
  930. [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey="00000000000000000400000000000000")]
  931. [Obsolete ("see CompressedStack class")]
  932. #if NET_1_1
  933. public
  934. #else
  935. internal
  936. #endif
  937. void SetCompressedStack (CompressedStack stack)
  938. {
  939. ExecutionContext.SecurityContext.CompressedStack = stack;
  940. }
  941. #endif
  942. #if NET_1_1
  943. void _Thread.GetIDsOfNames ([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
  944. {
  945. throw new NotImplementedException ();
  946. }
  947. void _Thread.GetTypeInfo (uint iTInfo, uint lcid, IntPtr ppTInfo)
  948. {
  949. throw new NotImplementedException ();
  950. }
  951. void _Thread.GetTypeInfoCount (out uint pcTInfo)
  952. {
  953. throw new NotImplementedException ();
  954. }
  955. void _Thread.Invoke (uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams,
  956. IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
  957. {
  958. throw new NotImplementedException ();
  959. }
  960. #endif
  961. }
  962. }