1 // ThreadTest.cs - NUnit Test Cases for the System.Threading.Thread class
4 // Eduardo Garcia Cebollero (kiwnix@yahoo.es)
5 // Sebastien Pouliot <sebastien@ximian.com>
7 // (C) Eduardo Garcia Cebollero.
8 // (C) Ximian, Inc. http://www.ximian.com
9 // (C) 2004 Novell (http://www.novell.com)
13 using System.Globalization;
14 using System.Security.Principal;
15 using System.Threading;
16 using System.Reflection;
17 using System.Collections.Generic;
18 using SD = System.Diagnostics;
20 using NUnit.Framework;
22 namespace MonoTests.System.Threading
24 // These tests seem to hang the 2.0 framework. So they are disabled for now
25 // Don't reenable them until you can run a few thousand times on an SMP box.
26 [Category ("NotWorking")]
27 public class ThreadedPrincipalTest
29 public static void NoPrincipal ()
31 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.NoPrincipal);
32 IPrincipal p = Thread.CurrentPrincipal;
33 Assert.IsNull (p, "#1");
35 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
36 Assert.IsNotNull (Thread.CurrentPrincipal, "#2");
38 Thread.CurrentPrincipal = null;
39 Assert.IsNull (Thread.CurrentPrincipal, "#3");
40 // in this case we can return to null
43 public static void UnauthenticatedPrincipal ()
45 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.UnauthenticatedPrincipal);
46 IPrincipal p = Thread.CurrentPrincipal;
47 Assert.IsNotNull (p, "#1");
48 Assert.IsTrue ((p is GenericPrincipal), "#2");
49 Assert.AreEqual (String.Empty, p.Identity.Name, "#3");
50 Assert.AreEqual (String.Empty, p.Identity.AuthenticationType, "#4");
51 Assert.IsFalse (p.Identity.IsAuthenticated, "#5");
53 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
54 Assert.IsNotNull (Thread.CurrentPrincipal, "#6");
56 Thread.CurrentPrincipal = null;
57 Assert.IsNotNull (Thread.CurrentPrincipal, "#7");
58 // in this case we can't return to null
61 public static void WindowsPrincipal ()
63 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.WindowsPrincipal);
64 IPrincipal p = Thread.CurrentPrincipal;
65 Assert.IsNotNull (p, "#1");
66 Assert.IsTrue ((p is WindowsPrincipal), "#2");
67 Assert.IsNotNull (p.Identity.Name, "#3");
68 Assert.IsNotNull (p.Identity.AuthenticationType, "#4");
69 Assert.IsTrue (p.Identity.IsAuthenticated, "#5");
71 // note: we can switch from a WindowsPrincipal to a GenericPrincipal
72 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
73 Assert.IsNotNull (Thread.CurrentPrincipal, "#6");
75 Thread.CurrentPrincipal = null;
76 Assert.IsNotNull (Thread.CurrentPrincipal, "#7");
77 // in this case we can't return to null
80 public static void CopyOnNewThread ()
82 Assert.IsNotNull (Thread.CurrentPrincipal, "#1");
83 Assert.AreEqual ("good", Thread.CurrentPrincipal.Identity.Name, "#2");
88 [Category("MobileNotWorking")] // Abort #10240
89 public class ThreadTest
91 //TimeSpan Infinite = new TimeSpan (-10000); // -10000 ticks == -1 ms
92 TimeSpan SmallNegative = new TimeSpan (-2); // between 0 and -1.0 (infinite) ms
93 TimeSpan Negative = new TimeSpan (-20000); // really negative
94 //TimeSpan MaxValue = TimeSpan.FromMilliseconds ((long) Int32.MaxValue);
95 TimeSpan TooLarge = TimeSpan.FromMilliseconds ((long) Int32.MaxValue + 1);
97 //Some Classes to test as threads
101 public Thread thread1;
107 thread1 = (Thread)null;
109 endm1 = endm2 = false;
112 public void TestMethod()
120 public void TestMethod2()
122 if (!(thread1==(Thread)null) )
133 public bool run = false;
140 public void TestMethod()
155 public C1Test sub_class;
156 public Thread sub_thread;
160 sub_class = new C1Test();
161 sub_thread = new Thread(new ThreadStart(sub_class.TestMethod));
164 public void TestMethod1()
168 #if MONO_FEATURE_THREAD_ABORT
171 sub_thread.Interrupt ();
178 public C1Test class1;
179 public C1Test class2;
180 public Thread thread1;
181 public Thread thread2;
189 class1 = new C1Test();
190 class2 = new C1Test();
191 thread1 = new Thread(new ThreadStart(class1.TestMethod));
192 thread2 = new Thread(new ThreadStart(class2.TestMethod));
195 public void TestMethod1()
198 TestUtil.WaitForAlive (thread1, "wait1");
201 TestUtil.WaitForAlive (thread2, "wait2");
203 #if MONO_FEATURE_THREAD_ABORT
206 thread1.Interrupt ();
208 TestUtil.WaitForNotAlive (thread1, "wait3");
210 #if MONO_FEATURE_THREAD_ABORT
213 thread2.Interrupt ();
215 TestUtil.WaitForNotAlive (thread2, "wait4");
219 public void TestMethod2()
227 public void TestCtor1()
229 C1Test test1 = new C1Test();
230 Thread t = new Thread (new ThreadStart (test1.TestMethod));
232 Assert.IsTrue (t.CurrentCulture.IsReadOnly, "CurrentCulture.IsReadOnly");
233 Assert.IsFalse (t.IsAlive, "IsAlive");
234 Assert.IsFalse (t.IsBackground, "IsBackground");
235 Assert.IsNull (t.Name, "Name");
236 Assert.AreEqual (ThreadState.Unstarted, t.ThreadState, "ThreadState");
240 [Category ("NotWorking")] // we're not sharing (read-only) CultureInfo
241 public void CultureInfo_Shared_Across_Threads ()
243 Thread t = new Thread (TestCtor1);
244 Assert.AreSame (t.CurrentCulture, t.CurrentUICulture, "Culture");
246 Assert.AreSame (t.CurrentCulture, CultureInfo.CurrentCulture, "CultureInfo.CurrentCulture");
247 Assert.AreSame (t.CurrentUICulture, CultureInfo.CurrentUICulture, "CultureInfo.CurrentUICulture");
249 Assert.AreSame (t.CurrentCulture, Thread.CurrentThread.CurrentCulture, "Thread.CurrentThread.CurrentCulture");
250 Assert.AreSame (t.CurrentUICulture, Thread.CurrentThread.CurrentUICulture, "Thread.CurrentThread.CurrentUICulture");
253 [Test] // bug #325566
254 public void GetHashCodeTest ()
256 C1Test test1 = new C1Test ();
257 Thread tA = new Thread (new ThreadStart (test1.TestMethod));
258 int hA1 = tA.GetHashCode ();
259 Assert.IsTrue (hA1 > 0, "#A1");
261 int hA2 = tA.GetHashCode ();
262 Assert.AreEqual (hA1, hA2, "#A2");
264 int hA3 = tA.GetHashCode ();
265 Assert.AreEqual (hA1, hA3, "#A3");
266 Assert.AreEqual (hA1, tA.ManagedThreadId, "#A4");
268 test1 = new C1Test ();
269 Thread tB = new Thread (new ThreadStart (test1.TestMethod));
270 int hB1 = tB.GetHashCode ();
271 Assert.IsTrue (hB1 > 0, "#B1");
273 int hB2 = tB.GetHashCode ();
274 Assert.AreEqual (hB1, hB2, "#B2");
276 int hB3 = tB.GetHashCode ();
277 Assert.AreEqual (hB1, hB3, "#B3");
278 Assert.AreEqual (hB1, tB.ManagedThreadId, "#B4");
279 Assert.IsFalse (hA2 == hB2, "#B5");
283 public void ManagedThreadId ()
285 C1Test test1 = new C1Test ();
286 Thread t1 = new Thread (new ThreadStart (test1.TestMethod));
287 int mtA1 = t1.ManagedThreadId;
289 int mtA2 = t1.ManagedThreadId;
291 int mtA3 = t1.ManagedThreadId;
292 Assert.AreEqual (mtA1, mtA2, "#A1");
293 Assert.AreEqual (mtA2, mtA3, "#A2");
295 test1 = new C1Test ();
296 Thread t2 = new Thread (new ThreadStart (test1.TestMethod));
297 int mtB1 = t2.ManagedThreadId;
299 int mtB2 = t2.ManagedThreadId;
301 int mtB3 = t2.ManagedThreadId;
302 Assert.AreEqual (mtB1, mtB2, "#B1");
303 Assert.AreEqual (mtB2, mtB3, "#B2");
304 Assert.IsFalse (mtB1 == mtA1, "#B3");
308 [Category ("NotDotNet")] // it hangs.
309 public void TestStart()
312 C1Test test1 = new C1Test();
313 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
316 Assert.AreEqual (10, test1.cnt, "#1");
319 C2Test test1 = new C2Test();
320 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
322 #if MONO_FEATURE_THREAD_ABORT
325 TestThread.Interrupt ();
330 } catch (ThreadStateException) {
334 C2Test test1 = new C2Test();
335 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
339 bool started = (TestThread.ThreadState == ThreadState.Running);
340 Assert.AreEqual (started, test1.run, "#15 Thread Is not in the correct state: ");
341 #if MONO_FEATURE_THREAD_ABORT
344 TestThread.Interrupt ();
350 public void TestApartmentState ()
352 C2Test test1 = new C2Test();
353 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
354 Assert.AreEqual (ApartmentState.Unknown, TestThread.ApartmentState, "#1");
356 TestUtil.WaitForAlive (TestThread, "wait5");
357 Assert.AreEqual (ApartmentState.MTA, TestThread.ApartmentState, "#2");
358 #if MONO_FEATURE_THREAD_ABORT
361 TestThread.Interrupt ();
366 [Category ("NotWorking")] // setting the priority of a Thread before it is started isn't implemented in Mono yet
367 public void TestPriority1()
369 C2Test test1 = new C2Test();
370 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
372 TestThread.Priority=ThreadPriority.BelowNormal;
373 ThreadPriority before = TestThread.Priority;
374 Assert.AreEqual (ThreadPriority.BelowNormal, before, "#40 Unexpected priority before thread start: ");
376 TestUtil.WaitForAlive (TestThread, "wait7");
377 ThreadPriority after = TestThread.Priority;
378 Assert.AreEqual (before, after, "#41 Unexpected Priority Change: ");
380 #if MONO_FEATURE_THREAD_ABORT
383 TestThread.Interrupt ();
388 #if MONO_FEATURE_THREAD_ABORT
390 [Category ("NotDotNet")] // on MS, Thread is still in AbortRequested state when Start is invoked
391 public void AbortUnstarted ()
393 C2Test test1 = new C2Test();
394 Thread th = new Thread (new ThreadStart (test1.TestMethod));
401 [Category ("NotDotNet")] // on MS, ThreadState is immediately Stopped after Abort
402 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
403 public void TestPriority2()
405 C2Test test1 = new C2Test();
406 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
408 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#42 Incorrect Priority in New thread: ");
410 TestUtil.WaitForAliveOrStop (TestThread, "wait8");
411 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#43 Incorrect Priority in Started thread: ");
413 #if MONO_FEATURE_THREAD_ABORT
416 TestThread.Interrupt ();
419 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#44 Incorrect Priority in Aborted thread: ");
423 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
424 public void TestPriority3()
426 C2Test test1 = new C2Test();
427 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
430 TestThread.Priority = ThreadPriority.Lowest;
431 Assert.AreEqual (ThreadPriority.Lowest, TestThread.Priority, "#45A Incorrect Priority:");
432 TestThread.Priority = ThreadPriority.BelowNormal;
433 Assert.AreEqual (ThreadPriority.BelowNormal, TestThread.Priority, "#45B Incorrect Priority:");
434 TestThread.Priority = ThreadPriority.Normal;
435 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#45C Incorrect Priority:");
436 TestThread.Priority = ThreadPriority.AboveNormal;
437 Assert.AreEqual (ThreadPriority.AboveNormal, TestThread.Priority, "#45D Incorrect Priority:");
438 TestThread.Priority = ThreadPriority.Highest;
439 Assert.AreEqual (ThreadPriority.Highest, TestThread.Priority, "#45E Incorrect Priority:");
442 #if MONO_FEATURE_THREAD_ABORT
445 TestThread.Interrupt ();
451 public void TestUndivisibleByPageSizeMaxStackSize ()
453 const int undivisible_stacksize = 1048573;
455 var thread = new Thread (new ThreadStart (delegate {}), undivisible_stacksize);
461 public void TestIsBackground1 ()
463 C2Test test1 = new C2Test();
464 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
467 TestUtil.WaitForAlive (TestThread, "wait9");
468 bool state = TestThread.IsBackground;
469 Assert.IsFalse (state, "#51 IsBackground not set at the default state: ");
471 #if MONO_FEATURE_THREAD_ABORT
474 TestThread.Interrupt ();
480 public void TestIsBackground2 ()
482 C2Test test1 = new C2Test();
483 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
484 TestThread.IsBackground = true;
488 #if MONO_FEATURE_THREAD_ABORT
491 TestThread.Interrupt ();
495 if (TestThread.IsAlive) {
497 Assert.IsTrue (TestThread.IsBackground, "#52 Is Background Changed to Start ");
498 } catch (ThreadStateException) {
499 // Ignore if thread died meantime
505 public void TestName()
507 C2Test test1 = new C2Test();
508 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
511 TestUtil.WaitForAlive (TestThread, "wait10");
512 string name = TestThread.Name;
513 Assert.IsNull (name, "#61 Name set when mustn't be set: ");
514 string newname = "Testing....";
515 TestThread.Name = newname;
516 Assert.AreEqual (newname, TestThread.Name, "#62 Name not set when must be set: ");
518 #if MONO_FEATURE_THREAD_ABORT
521 TestThread.Interrupt ();
529 Thread t = new Thread (new ThreadStart (Name));
530 Assert.IsNull (t.Name, "Name-1");
532 Assert.IsNull (t.Name, "Name-2");
536 [ExpectedException (typeof (InvalidOperationException))]
537 public void Rename ()
539 Thread t = new Thread (new ThreadStart (Rename));
545 public void TestNestedThreads1()
547 C3Test test1 = new C3Test();
548 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
551 TestUtil.WaitForAlive (TestThread, "wait11");
553 #if MONO_FEATURE_THREAD_ABORT
556 TestThread.Interrupt ();
562 public void TestNestedThreads2()
564 C4Test test1 = new C4Test();
565 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
569 #if MONO_FEATURE_THREAD_ABORT
572 TestThread.Interrupt ();
578 public void TestJoin1()
580 C1Test test1 = new C1Test();
581 C1Test test2 = new C1Test();
582 Thread thread1 = new Thread(new ThreadStart(test1.TestMethod));
583 Thread thread2 = new Thread(new ThreadStart(test1.TestMethod2));
589 #if MONO_FEATURE_THREAD_ABORT
593 thread1.Interrupt ();
594 thread2.Interrupt ();
600 [ExpectedException (typeof (ArgumentOutOfRangeException))]
601 public void Join_Int32_Negative ()
603 // -1 is Timeout.Infinite
604 Thread.CurrentThread.Join (-2);
608 [ExpectedException (typeof (ArgumentOutOfRangeException))]
609 public void Join_TimeSpan_Negative ()
611 Thread.CurrentThread.Join (Negative);
615 [ExpectedException (typeof (ArgumentOutOfRangeException))]
616 public void Join_TimeSpan_TooLarge ()
618 Thread.CurrentThread.Join (TooLarge);
622 public void Join_TimeSpan_SmallNegative ()
624 Thread.CurrentThread.Join (SmallNegative);
628 [ExpectedException (typeof (ArgumentOutOfRangeException))]
629 public void Sleep_Int32_Negative ()
631 // -1 is Timeout.Infinite
636 public void Sleep_TimeSpan_SmallNegative ()
638 Thread.Sleep (SmallNegative);
642 [ExpectedException (typeof (ArgumentOutOfRangeException))]
643 public void Sleep_TimeSpan_Negative ()
645 Thread.Sleep (Negative);
649 [ExpectedException (typeof (ArgumentOutOfRangeException))]
650 public void Sleep_TimeSpan_TooLarge ()
652 Thread.Sleep (TooLarge);
656 public void SpinWait ()
658 // no exception for negative numbers
659 Thread.SpinWait (Int32.MinValue);
664 public void TestThreadState ()
666 //TODO: Test The rest of the possible transitions
667 C2Test test1 = new C2Test();
668 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
669 Assert.AreEqual (ThreadState.Unstarted, TestThread.ThreadState, "#101 Wrong Thread State");
672 //while(!TestThread.IsAlive); //In the MS Documentation this is not necessary
673 //but in the MS SDK it is
674 Assert.IsTrue (TestThread.ThreadState == ThreadState.Running || (TestThread.ThreadState & ThreadState.Unstarted) != 0,
675 "#102 Wrong Thread State: " + TestThread.ThreadState.ToString ());
677 #if MONO_FEATURE_THREAD_ABORT
680 TestThread.Interrupt ();
684 TestUtil.WaitForNotAlive (TestThread, "wait12");
685 // Docs say state will be Stopped, but Aborted happens sometimes (?)
686 Assert.IsTrue ((ThreadState.Stopped & TestThread.ThreadState) != 0 || (ThreadState.Aborted & TestThread.ThreadState) != 0,
687 "#103 Wrong Thread State: " + TestThread.ThreadState.ToString ());
691 [Ignore ("see comment below.")]
692 public void CurrentPrincipal_PrincipalPolicy_NoPrincipal ()
694 // note: switching from PrincipalPolicy won't work inside the same thread
695 // because as soon as a Principal object is created the Policy doesn't matter anymore
696 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.NoPrincipal));
701 #if MONO_FEATURE_THREAD_ABORT
710 [Ignore ("see comment below.")]
711 public void CurrentPrincipal_PrincipalPolicy_UnauthenticatedPrincipal ()
713 // note: switching from PrincipalPolicy won't work inside the same thread
714 // because as soon as a Principal object is created the Policy doesn't matter anymore
715 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.UnauthenticatedPrincipal));
720 #if MONO_FEATURE_THREAD_ABORT
729 public void CurrentPrincipal_PrincipalPolicy_WindowsPrincipal ()
731 // note: switching from PrincipalPolicy won't work inside the same thread
732 // because as soon as a Principal object is created the Policy doesn't matter anymore
733 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.WindowsPrincipal));
738 #if MONO_FEATURE_THREAD_ABORT
747 public void IPrincipal_CopyOnNewThread ()
749 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("bad"), null);
750 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.CopyOnNewThread));
752 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("good"), null);
756 #if MONO_FEATURE_THREAD_ABORT
766 #if MONO_FEATURE_THREAD_SUSPEND_RESUME
768 public void TestSuspend ()
770 Thread t = new Thread (new ThreadStart (DoCount));
771 t.IsBackground = true;
774 CheckIsRunning ("t1", t);
777 WaitSuspended ("t2", t);
779 CheckIsNotRunning ("t3", t);
782 WaitResumed ("t4", t);
784 CheckIsRunning ("t5", t);
787 TestUtil.WaitForNotAlive (t, "wait13");
788 CheckIsNotRunning ("t6", t);
792 #if MONO_FEATURE_THREAD_SUSPEND_RESUME && MONO_FEATURE_THREAD_ABORT
794 [Category("NotDotNet")] // On MS, ThreadStateException is thrown on Abort: "Thread is suspended; attempting to abort"
795 public void TestSuspendAbort ()
797 Thread t = new Thread (new ThreadStart (DoCount));
798 t.IsBackground = true;
801 CheckIsRunning ("t1", t);
804 WaitSuspended ("t2", t);
806 CheckIsNotRunning ("t3", t);
811 while (t.IsAlive && n < 200) {
816 Assert.IsTrue (n < 200, "Timeout while waiting for abort");
818 CheckIsNotRunning ("t6", t);
823 public void Test_Interrupt ()
825 ManualResetEvent mre = new ManualResetEvent (false);
826 bool interruptedExceptionThrown = false;
828 ThreadPool.QueueUserWorkItem (Test_Interrupt_Worker, Thread.CurrentThread);
836 } catch (ThreadInterruptedException) {
837 Assert.Fail ("ThreadInterruptedException thrown twice");
840 } catch (ThreadInterruptedException) {
841 interruptedExceptionThrown = true;
844 Assert.IsTrue (interruptedExceptionThrown, "ThreadInterruptedException expected.");
848 [ExpectedException (typeof (ArgumentNullException))]
849 public void TestQueueUserWorkItemNullCallback ()
851 ThreadPool.QueueUserWorkItem (null, null);
854 private void Test_Interrupt_Worker (object o)
856 Thread t = o as Thread;
862 public void Test_InterruptCurrentThread ()
864 ManualResetEvent mre = new ManualResetEvent (false);
865 bool interruptedExceptionThrown = false;
867 Thread.CurrentThread.Interrupt ();
871 } catch (ThreadInterruptedException) {
876 public void GetNamedDataSlotTest ()
878 Assert.IsNotNull (Thread.GetNamedDataSlot ("te#st"), "#1");
879 Assert.AreSame (Thread.GetNamedDataSlot ("te#st"), Thread.GetNamedDataSlot ("te#st"), "#2");
882 class DomainClass : MarshalByRefObject {
887 m_thread = new Thread(ThreadProc);
888 m_thread.Start(Thread.CurrentThread);
893 public void ThreadProc (object arg) {
894 success = m_thread == Thread.CurrentThread;
898 #if MONO_FEATURE_MULTIPLE_APPDOMAINS
900 [Category ("NotDotNet")]
901 public void CurrentThread_Domains ()
903 AppDomain ad = AppDomain.CreateDomain ("foo");
904 ad.Load (typeof (DomainClass).Assembly.GetName ());
905 var o = (DomainClass)ad.CreateInstanceAndUnwrap (typeof (DomainClass).Assembly.FullName, typeof (DomainClass).FullName);
906 Assert.IsTrue (o.Run ());
907 AppDomain.Unload (ad);
909 #endif // MONO_FEATURE_MULTIPLE_APPDOMAINS
911 void CheckIsRunning (string s, Thread t)
915 Assert.IsTrue (counter > c, s);
918 void CheckIsNotRunning (string s, Thread t)
922 Assert.AreEqual (counter, c, s);
925 void WaitSuspended (string s, Thread t)
928 ThreadState state = t.ThreadState;
929 while ((state & ThreadState.Suspended) == 0) {
930 Assert.IsTrue ((state & ThreadState.SuspendRequested) != 0, s + ": expected SuspendRequested state");
933 Assert.IsTrue (n < 100, s + ": failed to suspend");
934 state = t.ThreadState;
936 Assert.IsTrue ((state & ThreadState.SuspendRequested) == 0, s + ": SuspendRequested state not expected");
939 void WaitResumed (string s, Thread t)
942 while ((t.ThreadState & ThreadState.Suspended) != 0) {
945 Assert.IsTrue (n < 100, s + ": failed to resume");
949 public void DoCount ()
959 public class ThreadStateTest {
965 public void IsBackGround ()
967 Thread t1 = new Thread (new ThreadStart (Start));
968 Assert.AreEqual (ThreadState.Unstarted, t1.ThreadState, "#A1");
969 Assert.IsFalse (t1.IsBackground, "#A2");
972 Assert.AreEqual (ThreadState.Stopped, t1.ThreadState, "#A3");
975 bool isBackGround = t1.IsBackground;
976 Assert.Fail ("#A4: " + isBackGround.ToString ());
977 } catch (ThreadStateException ex) {
978 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A5");
979 Assert.IsNull (ex.InnerException, "#A6");
980 Assert.IsNotNull (ex.Message, "#A7");
983 Thread t2 = new Thread (new ThreadStart (Start));
984 Assert.AreEqual (ThreadState.Unstarted, t2.ThreadState, "#B1");
985 t2.IsBackground = true;
986 Assert.AreEqual (ThreadState.Unstarted | ThreadState.Background, t2.ThreadState, "#B2");
987 Assert.IsTrue (t2.IsBackground, "#B3");
990 Assert.AreEqual (ThreadState.Stopped, t2.ThreadState, "#B4");
993 bool isBackGround = t2.IsBackground;
994 Assert.Fail ("#B5: " + isBackGround.ToString ());
995 } catch (ThreadStateException ex) {
996 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B6");
997 Assert.IsNull (ex.InnerException, "#B7");
998 Assert.IsNotNull (ex.Message, "#B8");
1005 public class ThreadTest_ManagedThreadId
1009 MBRO mbro = new MBRO ();
1011 class MBRO : MarshalByRefObject {
1015 public string ad_a1;
1016 public string ad_b1;
1017 public string ad_b2;
1018 public string message;
1022 public void ManagedThreadId_AppDomains ()
1024 AppDomain currentDomain = AppDomain.CurrentDomain;
1025 ad1 = AppDomain.CreateDomain ("AppDomain 1", currentDomain.Evidence, currentDomain.SetupInformation);
1026 ad2 = AppDomain.CreateDomain ("AppDomain 2", currentDomain.Evidence, currentDomain.SetupInformation);
1028 Thread a = new Thread (ThreadA);
1029 Thread b = new Thread (ThreadB);
1030 // execute on AppDomain 1 thread A
1031 // execute on AppDomain 2 thread B
1032 // execute on AppDomain 1 thread B - must have same ManagedThreadId as Ad 2 on thread B
1038 AppDomain.Unload (ad1);
1039 AppDomain.Unload (ad2);
1041 if (mbro.message != null)
1042 Assert.Fail (mbro.message);
1044 // Console.WriteLine ("Done id_a1: {0} id_b1: {1} id_b2: {2} ad_a1: {3} ad_b1: {4} ad_b2: {5}", mbro.id_a1, mbro.id_b1, mbro.id_b2, mbro.ad_a1, mbro.ad_b1, mbro.ad_b2);
1046 Assert.AreEqual ("AppDomain 1", mbro.ad_a1, "Name #1");
1047 Assert.AreEqual ("AppDomain 1", mbro.ad_b1, "Name #2");
1048 Assert.AreEqual ("AppDomain 2", mbro.ad_b2, "Name #3");
1050 Assert.AreNotEqual (mbro.id_a1, mbro.id_b1, "Id #1");
1051 Assert.AreNotEqual (mbro.id_a1, mbro.id_b2, "Id #2");
1052 Assert.AreEqual (mbro.id_b1, mbro.id_b2, "Id #3");
1054 Assert.AreNotEqual (mbro.id_a1, Thread.CurrentThread.ManagedThreadId, "Id #4");
1055 Assert.AreNotEqual (mbro.id_b1, Thread.CurrentThread.ManagedThreadId, "Id #5");
1056 Assert.AreNotEqual (mbro.id_b2, Thread.CurrentThread.ManagedThreadId, "Id #6");
1057 Assert.AreNotEqual (mbro.ad_a1, AppDomain.CurrentDomain.FriendlyName, "Name #4");
1058 Assert.AreNotEqual (mbro.ad_b1, AppDomain.CurrentDomain.FriendlyName, "Name #5");
1059 Assert.AreNotEqual (mbro.ad_b2, AppDomain.CurrentDomain.FriendlyName, "Name #6");
1064 mbro.id_a1 = Thread.CurrentThread.ManagedThreadId;
1065 mbro.ad_a1 = AppDomain.CurrentDomain.FriendlyName;
1070 mbro.id_b2 = Thread.CurrentThread.ManagedThreadId;
1071 mbro.ad_b2 = AppDomain.CurrentDomain.FriendlyName;
1076 mbro.id_b1 = Thread.CurrentThread.ManagedThreadId;
1077 mbro.ad_b1 = AppDomain.CurrentDomain.FriendlyName;
1080 void ThreadA (object obj)
1082 // Console.WriteLine ("ThreadA");
1084 ad1.DoCallBack (A1);
1085 } catch (Exception ex) {
1086 mbro.message = string.Format ("ThreadA exception: {0}", ex);
1088 // Console.WriteLine ("ThreadA Done");
1091 void ThreadB (object obj)
1093 // Console.WriteLine ("ThreadB");
1095 ad2.DoCallBack (B2);
1096 ad1.DoCallBack (B1);
1097 } catch (Exception ex) {
1098 mbro.message = string.Format ("ThreadB exception: {0}", ex);
1100 // Console.WriteLine ("ThreadB Done");
1105 public class ThreadApartmentTest
1111 [Test] // bug #81658
1112 public void ApartmentState_StoppedThread ()
1114 Thread t1 = new Thread (new ThreadStart (Start));
1118 ApartmentState state = t1.ApartmentState;
1119 Assert.Fail ("#A1: " + state.ToString ());
1120 } catch (ThreadStateException ex) {
1121 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A2");
1122 Assert.IsNull (ex.InnerException, "#A3");
1123 Assert.IsNotNull (ex.Message, "#A4");
1126 Thread t2 = new Thread (new ThreadStart (Start));
1127 t2.IsBackground = true;
1131 ApartmentState state = t2.ApartmentState;
1132 Assert.Fail ("#B1: " + state.ToString ());
1133 } catch (ThreadStateException ex) {
1134 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B2");
1135 Assert.IsNull (ex.InnerException, "#B3");
1136 Assert.IsNotNull (ex.Message, "#B4");
1141 public void ApartmentState_BackGround ()
1143 Thread t1 = new Thread (new ThreadStart (Start));
1144 t1.IsBackground = true;
1145 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "#1");
1146 t1.ApartmentState = ApartmentState.STA;
1147 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#2");
1151 public void TestApartmentState ()
1153 Thread t1 = new Thread (new ThreadStart (Start));
1154 Thread t2 = new Thread (new ThreadStart (Start));
1155 Thread t3 = new Thread (new ThreadStart (Start));
1157 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "Thread1 Default");
1158 Assert.AreEqual (ApartmentState.Unknown, t2.ApartmentState, "Thread2 Default");
1159 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Default");
1161 t1.ApartmentState = ApartmentState.STA;
1162 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1163 t1.ApartmentState = ApartmentState.MTA;
1164 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Twice");
1166 t2.ApartmentState = ApartmentState.MTA;
1167 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Once");
1168 t2.ApartmentState = ApartmentState.STA;
1169 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Twice");
1171 bool exception_occured = false;
1173 t3.ApartmentState = ApartmentState.Unknown;
1176 exception_occured = true;
1178 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Set Invalid");
1179 Assert.IsFalse (exception_occured, "Thread3 Set Invalid Exception Occured");
1182 exception_occured = false;
1184 t1.ApartmentState = ApartmentState.STA;
1187 exception_occured = true;
1189 Assert.IsTrue (exception_occured, "Thread1 Started Invalid Exception Occured");
1193 public void TestSetApartmentStateSameState ()
1195 Thread t1 = new Thread (new ThreadStart (Start));
1196 t1.SetApartmentState (ApartmentState.STA);
1197 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1199 t1.SetApartmentState (ApartmentState.STA);
1200 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set twice");
1204 [ExpectedException(typeof(InvalidOperationException))]
1205 public void TestSetApartmentStateDiffState ()
1207 Thread t1 = new Thread (new ThreadStart (Start));
1208 t1.SetApartmentState (ApartmentState.STA);
1209 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1211 t1.SetApartmentState (ApartmentState.MTA);
1215 public void TestTrySetApartmentState ()
1217 Thread t1 = new Thread (new ThreadStart (Start));
1218 t1.SetApartmentState (ApartmentState.STA);
1219 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1221 bool result = t1.TrySetApartmentState (ApartmentState.MTA);
1222 Assert.IsFalse (result, "#2");
1224 result = t1.TrySetApartmentState (ApartmentState.STA);
1225 Assert.IsTrue (result, "#3");
1229 public void TestTrySetApartmentStateRunning ()
1231 Thread t1 = new Thread (new ThreadStart (Start));
1232 t1.SetApartmentState (ApartmentState.STA);
1233 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1238 t1.TrySetApartmentState (ApartmentState.STA);
1240 } catch (ThreadStateException) {
1247 public void Volatile () {
1249 Thread.VolatileWrite (ref v3, double.MaxValue);
1250 Assert.AreEqual (v3, double.MaxValue);
1253 Thread.VolatileWrite (ref v4, float.MaxValue);
1254 Assert.AreEqual (v4, float.MaxValue);
1258 public void Culture ()
1260 Assert.IsNotNull (Thread.CurrentThread.CurrentCulture, "CurrentCulture");
1261 Assert.IsNotNull (Thread.CurrentThread.CurrentUICulture, "CurrentUICulture");
1265 public void ThreadStartSimple ()
1268 Thread t = new Thread (delegate () {
1269 // ensure the NSAutoreleasePool works
1274 Assert.AreEqual (1, i, "ThreadStart");
1278 public void ParametrizedThreadStart ()
1282 Thread t = new Thread (delegate (object obj) {
1283 // ensure the NSAutoreleasePool works
1290 Assert.AreEqual (1, i, "ParametrizedThreadStart");
1291 Assert.AreEqual (this, arg, "obj");
1295 public void SetNameTpThread () {
1296 ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
1299 static void ThreadProc(Object stateInfo) {
1300 Thread.CurrentThread.Name = "My Worker";
1304 public void GetStackTraces () {
1305 var m = typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static);
1307 var res = (Dictionary<Thread,SD.StackTrace>)typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static).Invoke (null, null);
1308 foreach (var t in res.Keys) {
1309 var st = res [t].ToString ();
1315 public class TestUtil
1317 public static void WaitForNotAlive (Thread t, string s)
1319 WhileAlive (t, true, s);
1322 public static void WaitForAlive (Thread t, string s)
1324 WhileAlive (t, false, s);
1327 public static bool WaitForAliveOrStop (Thread t, string s)
1329 return WhileAliveOrStop (t, false, s);
1332 public static void WhileAlive (Thread t, bool alive, string s)
1334 DateTime ti = DateTime.Now;
1335 while (t.IsAlive == alive) {
1336 if ((DateTime.Now - ti).TotalSeconds > 10) {
1337 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1338 else Assert.Fail ("Timeout while waiting for alive state. " + s);
1343 public static bool WhileAliveOrStop (Thread t, bool alive, string s)
1345 DateTime ti = DateTime.Now;
1346 while (t.IsAlive == alive) {
1347 if (t.ThreadState == ThreadState.Stopped)
1350 if ((DateTime.Now - ti).TotalSeconds > 10) {
1351 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1352 else Assert.Fail ("Timeout while waiting for alive state. " + s);