Thread.cs 34 KB

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