Thread.cs 35 KB

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