Thread.cs 31 KB

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