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;
17 using NUnit.Framework;
19 namespace MonoTests.System.Threading
21 // These tests seem to hang the 2.0 framework. So they are disabled for now
22 // Don't reenable them until you can run a few thousand times on an SMP box.
23 [Category ("NotWorking")]
24 public class ThreadedPrincipalTest
26 public static void NoPrincipal ()
28 #if !TARGET_JVM // AppDomain.SetPrincipalPolicy not supported for TARGET_JVM
29 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.NoPrincipal);
31 IPrincipal p = Thread.CurrentPrincipal;
32 Assert.IsNull (p, "#1");
34 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
35 Assert.IsNotNull (Thread.CurrentPrincipal, "#2");
37 Thread.CurrentPrincipal = null;
38 Assert.IsNull (Thread.CurrentPrincipal, "#3");
39 // in this case we can return to null
42 #if !TARGET_JVM // AppDomain.SetPrincipalPolicy not supported for TARGET_JVM
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
81 public static void CopyOnNewThread ()
83 Assert.IsNotNull (Thread.CurrentPrincipal, "#1");
84 Assert.AreEqual ("good", Thread.CurrentPrincipal.Identity.Name, "#2");
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);
102 switch (Environment.OSVersion.Platform) {
103 case PlatformID.Win32NT:
104 case PlatformID.Win32S:
105 case PlatformID.Win32Windows:
106 case PlatformID.WinCE:
111 // check a class in mscorlib to determine if we're running on Mono
112 if (Type.GetType ("System.MonoType", false) != null)
116 //Some Classes to test as threads
120 public Thread thread1;
126 thread1 = (Thread)null;
128 endm1 = endm2 = false;
131 public void TestMethod()
139 public void TestMethod2()
141 if (!(thread1==(Thread)null) )
152 public bool run = false;
159 public void TestMethod()
174 public C1Test sub_class;
175 public Thread sub_thread;
179 sub_class = new C1Test();
180 sub_thread = new Thread(new ThreadStart(sub_class.TestMethod));
183 public void TestMethod1()
193 public C1Test class1;
194 public C1Test class2;
195 public Thread thread1;
196 public Thread thread2;
204 class1 = new C1Test();
205 class2 = new C1Test();
206 thread1 = new Thread(new ThreadStart(class1.TestMethod));
207 thread2 = new Thread(new ThreadStart(class2.TestMethod));
210 public void TestMethod1()
213 TestUtil.WaitForAlive (thread1, "wait1");
216 TestUtil.WaitForAlive (thread2, "wait2");
219 TestUtil.WaitForNotAlive (thread1, "wait3");
222 TestUtil.WaitForNotAlive (thread2, "wait4");
226 public void TestMethod2()
234 public void TestCtor1()
236 C1Test test1 = new C1Test();
237 Thread t = new Thread (new ThreadStart (test1.TestMethod));
239 Assert.IsTrue (t.CurrentCulture.IsReadOnly, "CurrentCulture.IsReadOnly");
240 Assert.IsFalse (t.IsAlive, "IsAlive");
241 Assert.IsFalse (t.IsBackground, "IsBackground");
242 Assert.IsNull (t.Name, "Name");
243 Assert.AreEqual (ThreadState.Unstarted, t.ThreadState, "ThreadState");
247 [Category ("NotWorking")] // we're not sharing (read-only) CultureInfo
248 public void CultureInfo_Shared_Across_Threads ()
250 Thread t = new Thread (TestCtor1);
251 Assert.AreSame (t.CurrentCulture, t.CurrentUICulture, "Culture");
253 Assert.AreSame (t.CurrentCulture, CultureInfo.CurrentCulture, "CultureInfo.CurrentCulture");
254 Assert.AreSame (t.CurrentUICulture, CultureInfo.CurrentUICulture, "CultureInfo.CurrentUICulture");
256 Assert.AreSame (t.CurrentCulture, Thread.CurrentThread.CurrentCulture, "Thread.CurrentThread.CurrentCulture");
257 Assert.AreSame (t.CurrentUICulture, Thread.CurrentThread.CurrentUICulture, "Thread.CurrentThread.CurrentUICulture");
260 [Test] // bug #325566
261 public void GetHashCodeTest ()
263 C1Test test1 = new C1Test ();
264 Thread tA = new Thread (new ThreadStart (test1.TestMethod));
265 int hA1 = tA.GetHashCode ();
267 Assert.IsTrue (hA1 > 0, "#A1");
270 int hA2 = tA.GetHashCode ();
271 Assert.AreEqual (hA1, hA2, "#A2");
273 int hA3 = tA.GetHashCode ();
274 Assert.AreEqual (hA1, hA3, "#A3");
276 Assert.AreEqual (hA1, tA.ManagedThreadId, "#A4");
279 test1 = new C1Test ();
280 Thread tB = new Thread (new ThreadStart (test1.TestMethod));
281 int hB1 = tB.GetHashCode ();
283 Assert.IsTrue (hB1 > 0, "#B1");
286 int hB2 = tB.GetHashCode ();
287 Assert.AreEqual (hB1, hB2, "#B2");
289 int hB3 = tB.GetHashCode ();
290 Assert.AreEqual (hB1, hB3, "#B3");
292 Assert.AreEqual (hB1, tB.ManagedThreadId, "#B4");
294 Assert.IsFalse (hA2 == hB2, "#B5");
299 public void ManagedThreadId ()
301 C1Test test1 = new C1Test ();
302 Thread t1 = new Thread (new ThreadStart (test1.TestMethod));
303 int mtA1 = t1.ManagedThreadId;
305 int mtA2 = t1.ManagedThreadId;
307 int mtA3 = t1.ManagedThreadId;
308 Assert.AreEqual (mtA1, mtA2, "#A1");
309 Assert.AreEqual (mtA2, mtA3, "#A2");
311 test1 = new C1Test ();
312 Thread t2 = new Thread (new ThreadStart (test1.TestMethod));
313 int mtB1 = t2.ManagedThreadId;
315 int mtB2 = t2.ManagedThreadId;
317 int mtB3 = t2.ManagedThreadId;
318 Assert.AreEqual (mtB1, mtB2, "#B1");
319 Assert.AreEqual (mtB2, mtB3, "#B2");
320 Assert.IsFalse (mtB1 == mtA1, "#B3");
325 [Category ("NotDotNet")] // it hangs.
326 public void TestStart()
328 if (is_win32 && is_mono)
329 Assert.Fail ("This test fails on Win32. The test should be fixed.");
331 C1Test test1 = new C1Test();
332 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
335 Assert.AreEqual (10, test1.cnt, "#1");
338 C2Test test1 = new C2Test();
339 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
345 } catch (ThreadStateException) {
349 C2Test test1 = new C2Test();
350 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
354 bool started = (TestThread.ThreadState == ThreadState.Running);
355 Assert.AreEqual (started, test1.run, "#15 Thread Is not in the correct state: ");
361 public void TestApartmentState ()
363 if (is_win32 && is_mono)
364 Assert.Fail ("This test fails on mono on win32. Our runtime should be fixed.");
366 C2Test test1 = new C2Test();
367 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
368 Assert.AreEqual (ApartmentState.Unknown, TestThread.ApartmentState, "#1");
370 TestUtil.WaitForAlive (TestThread, "wait5");
372 Assert.AreEqual (ApartmentState.MTA, TestThread.ApartmentState, "#2");
374 Assert.AreEqual (ApartmentState.Unknown, TestThread.ApartmentState, "#3");
380 public void TestPriority1()
382 if (is_win32 && is_mono)
383 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
385 C2Test test1 = new C2Test();
386 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
388 TestThread.Priority=ThreadPriority.BelowNormal;
389 ThreadPriority after = TestThread.Priority;
391 TestUtil.WaitForAlive (TestThread, "wait7");
392 ThreadPriority before = TestThread.Priority;
393 Assert.AreEqual (before, after, "#41 Unexpected Priority Change: ");
400 [Category ("NotDotNet")] // on MS, Thread is still in AbortRequested state when Start is invoked
401 public void AbortUnstarted ()
403 C2Test test1 = new C2Test();
404 Thread th = new Thread (new ThreadStart (test1.TestMethod));
410 [Category ("NotDotNet")] // on MS, ThreadState is immediately Stopped after Abort
411 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
412 public void TestPriority2()
414 C2Test test1 = new C2Test();
415 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
417 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#42 Incorrect Priority in New thread: ");
419 TestUtil.WaitForAliveOrStop (TestThread, "wait8");
420 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#43 Incorrect Priority in Started thread: ");
424 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#44 Incorrect Priority in Aborted thread: ");
428 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
429 public void TestPriority3()
431 C2Test test1 = new C2Test();
432 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
435 TestThread.Priority = ThreadPriority.Lowest;
436 Assert.AreEqual (ThreadPriority.Lowest, TestThread.Priority, "#45A Incorrect Priority:");
437 TestThread.Priority = ThreadPriority.BelowNormal;
438 Assert.AreEqual (ThreadPriority.BelowNormal, TestThread.Priority, "#45B Incorrect Priority:");
439 TestThread.Priority = ThreadPriority.Normal;
440 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#45C Incorrect Priority:");
441 TestThread.Priority = ThreadPriority.AboveNormal;
442 Assert.AreEqual (ThreadPriority.AboveNormal, TestThread.Priority, "#45D Incorrect Priority:");
443 TestThread.Priority = ThreadPriority.Highest;
444 Assert.AreEqual (ThreadPriority.Highest, TestThread.Priority, "#45E Incorrect Priority:");
452 public void TestUndivisibleByPageSizeMaxStackSize ()
454 const int undivisible_stacksize = 1048573;
456 var thread = new Thread (new ThreadStart (delegate {}), undivisible_stacksize);
462 public void TestIsBackground1 ()
464 if (is_win32 && is_mono)
465 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
467 C2Test test1 = new C2Test();
468 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
471 TestUtil.WaitForAlive (TestThread, "wait9");
472 bool state = TestThread.IsBackground;
473 Assert.IsFalse (state, "#51 IsBackground not set at the default state: ");
480 public void TestIsBackground2 ()
482 C2Test test1 = new C2Test();
483 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
484 TestThread.IsBackground = true;
491 if (TestThread.IsAlive)
492 Assert.IsTrue (TestThread.IsBackground, "#52 Is Background Changed to Start ");
496 public void TestName()
498 if (is_win32 && is_mono)
499 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
501 C2Test test1 = new C2Test();
502 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
505 TestUtil.WaitForAlive (TestThread, "wait10");
506 string name = TestThread.Name;
507 Assert.IsNull (name, "#61 Name set when mustn't be set: ");
508 string newname = "Testing....";
509 TestThread.Name = newname;
510 Assert.AreEqual (newname, TestThread.Name, "#62 Name not set when must be set: ");
519 Thread t = new Thread (new ThreadStart (Name));
520 Assert.IsNull (t.Name, "Name-1");
522 Assert.IsNull (t.Name, "Name-2");
526 [ExpectedException (typeof (InvalidOperationException))]
527 public void ReName ()
529 Thread t = new Thread (new ThreadStart (ReName));
535 public void TestNestedThreads1()
537 C3Test test1 = new C3Test();
538 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
541 TestUtil.WaitForAlive (TestThread, "wait11");
548 public void TestNestedThreads2()
550 C4Test test1 = new C4Test();
551 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
560 public void TestJoin1()
562 C1Test test1 = new C1Test();
563 C1Test test2 = new C1Test();
564 Thread thread1 = new Thread(new ThreadStart(test1.TestMethod));
565 Thread thread2 = new Thread(new ThreadStart(test1.TestMethod2));
577 [ExpectedException (typeof (ArgumentOutOfRangeException))]
578 public void Join_Int32_Negative ()
580 // -1 is Timeout.Infinite
581 Thread.CurrentThread.Join (-2);
585 [ExpectedException (typeof (ArgumentOutOfRangeException))]
586 public void Join_TimeSpan_Negative ()
588 Thread.CurrentThread.Join (Negative);
592 [ExpectedException (typeof (ArgumentOutOfRangeException))]
593 public void Join_TimeSpan_TooLarge ()
595 Thread.CurrentThread.Join (TooLarge);
599 public void Join_TimeSpan_SmallNegative ()
601 Thread.CurrentThread.Join (SmallNegative);
605 [ExpectedException (typeof (ArgumentOutOfRangeException))]
606 public void Sleep_Int32_Negative ()
608 // -1 is Timeout.Infinite
613 public void Sleep_TimeSpan_SmallNegative ()
615 Thread.Sleep (SmallNegative);
619 [ExpectedException (typeof (ArgumentOutOfRangeException))]
620 public void Sleep_TimeSpan_Negative ()
622 Thread.Sleep (Negative);
626 [ExpectedException (typeof (ArgumentOutOfRangeException))]
627 public void Sleep_TimeSpan_TooLarge ()
629 Thread.Sleep (TooLarge);
633 public void SpinWait ()
635 // no exception for negative numbers
636 Thread.SpinWait (Int32.MinValue);
641 public void TestThreadState ()
643 if (is_win32 && is_mono)
644 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
646 //TODO: Test The rest of the possible transitions
647 C2Test test1 = new C2Test();
648 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
649 Assert.AreEqual (ThreadState.Unstarted, TestThread.ThreadState, "#101 Wrong Thread State");
652 //while(!TestThread.IsAlive); //In the MS Documentation this is not necessary
653 //but in the MS SDK it is
654 Assert.IsTrue (TestThread.ThreadState == ThreadState.Running || (TestThread.ThreadState & ThreadState.Unstarted) != 0,
655 "#102 Wrong Thread State: " + TestThread.ThreadState.ToString ());
660 TestUtil.WaitForNotAlive (TestThread, "wait12");
661 // Docs say state will be Stopped, but Aborted happens sometimes (?)
662 Assert.IsTrue ((ThreadState.Stopped & TestThread.ThreadState) != 0 || (ThreadState.Aborted & TestThread.ThreadState) != 0,
663 "#103 Wrong Thread State: " + TestThread.ThreadState.ToString ());
667 [Ignore ("see comment below.")]
668 public void CurrentPrincipal_PrincipalPolicy_NoPrincipal ()
670 // note: switching from PrincipalPolicy won't work inside the same thread
671 // because as soon as a Principal object is created the Policy doesn't matter anymore
672 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.NoPrincipal));
681 #if !TARGET_JVM // AppDomain.SetPrincipalPolicy not supported for TARGET_JVM
683 [Ignore ("see comment below.")]
684 public void CurrentPrincipal_PrincipalPolicy_UnauthenticatedPrincipal ()
686 // note: switching from PrincipalPolicy won't work inside the same thread
687 // because as soon as a Principal object is created the Policy doesn't matter anymore
688 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.UnauthenticatedPrincipal));
698 public void CurrentPrincipal_PrincipalPolicy_WindowsPrincipal ()
700 // note: switching from PrincipalPolicy won't work inside the same thread
701 // because as soon as a Principal object is created the Policy doesn't matter anymore
702 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.WindowsPrincipal));
713 public void IPrincipal_CopyOnNewThread ()
715 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("bad"), null);
716 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.CopyOnNewThread));
718 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("good"), null);
729 public void TestSuspend ()
731 Thread t = new Thread (new ThreadStart (DoCount));
732 t.IsBackground = true;
735 CheckIsRunning ("t1", t);
738 WaitSuspended ("t2", t);
740 CheckIsNotRunning ("t3", t);
743 WaitResumed ("t4", t);
745 CheckIsRunning ("t5", t);
748 TestUtil.WaitForNotAlive (t, "wait13");
749 CheckIsNotRunning ("t6", t);
753 [Category("NotDotNet")] // On MS, ThreadStateException is thrown on Abort: "Thread is suspended; attempting to abort"
754 public void TestSuspendAbort ()
756 if (is_win32 && is_mono)
757 Assert.Fail ("This test fails on Win32. The test should be fixed.");
759 Thread t = new Thread (new ThreadStart (DoCount));
760 t.IsBackground = true;
763 CheckIsRunning ("t1", t);
766 WaitSuspended ("t2", t);
768 CheckIsNotRunning ("t3", t);
773 while (t.IsAlive && n < 200) {
778 Assert.IsTrue (n < 200, "Timeout while waiting for abort");
780 CheckIsNotRunning ("t6", t);
784 public void Test_Interrupt ()
786 bool interruptedExceptionThrown = false;
787 ThreadPool.QueueUserWorkItem (Test_Interrupt_Worker, Thread.CurrentThread);
795 } catch (ThreadInterruptedException) {
796 Assert.Fail ("ThreadInterruptedException thrown twice");
799 } catch (ThreadInterruptedException) {
800 interruptedExceptionThrown = true;
803 Assert.IsTrue (interruptedExceptionThrown, "ThreadInterruptedException expected.");
807 [ExpectedException (typeof (ArgumentNullException))]
808 public void TestQueueUserWorkItemNullCallback ()
810 ThreadPool.QueueUserWorkItem (null, null);
813 private void Test_Interrupt_Worker (object o)
815 Thread t = o as Thread;
821 [Category ("NotDotNet")] // it crashes nunit.
822 public void Test_InterruptCurrentThread ()
824 bool interruptedExceptionThrown = false;
826 Thread.CurrentThread.Interrupt ();
830 } catch (ThreadInterruptedException) {
834 void CheckIsRunning (string s, Thread t)
838 Assert.IsTrue (counter > c, s);
841 void CheckIsNotRunning (string s, Thread t)
845 Assert.AreEqual (counter, c, s);
848 void WaitSuspended (string s, Thread t)
851 ThreadState state = t.ThreadState;
852 while ((state & ThreadState.Suspended) == 0) {
853 Assert.IsTrue ((state & ThreadState.SuspendRequested) != 0, s + ": expected SuspendRequested state");
856 Assert.IsTrue (n < 100, s + ": failed to suspend");
857 state = t.ThreadState;
859 Assert.IsTrue ((state & ThreadState.SuspendRequested) == 0, s + ": SuspendRequested state not expected");
862 void WaitResumed (string s, Thread t)
865 while ((t.ThreadState & ThreadState.Suspended) != 0) {
868 Assert.IsTrue (n < 100, s + ": failed to resume");
872 public void DoCount ()
882 public class ThreadStateTest {
888 public void IsBackGround ()
890 Thread t1 = new Thread (new ThreadStart (Start));
891 Assert.AreEqual (ThreadState.Unstarted, t1.ThreadState, "#A1");
892 Assert.IsFalse (t1.IsBackground, "#A2");
895 Assert.AreEqual (ThreadState.Stopped, t1.ThreadState, "#A3");
898 bool isBackGround = t1.IsBackground;
899 Assert.Fail ("#A4: " + isBackGround.ToString ());
900 } catch (ThreadStateException ex) {
901 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A5");
902 Assert.IsNull (ex.InnerException, "#A6");
903 Assert.IsNotNull (ex.Message, "#A7");
906 Thread t2 = new Thread (new ThreadStart (Start));
907 Assert.AreEqual (ThreadState.Unstarted, t2.ThreadState, "#B1");
908 t2.IsBackground = true;
909 Assert.AreEqual (ThreadState.Unstarted | ThreadState.Background, t2.ThreadState, "#B2");
910 Assert.IsTrue (t2.IsBackground, "#B3");
913 Assert.AreEqual (ThreadState.Stopped, t2.ThreadState, "#B4");
916 bool isBackGround = t2.IsBackground;
917 Assert.Fail ("#B5: " + isBackGround.ToString ());
918 } catch (ThreadStateException ex) {
919 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B6");
920 Assert.IsNull (ex.InnerException, "#B7");
921 Assert.IsNotNull (ex.Message, "#B8");
928 public class ThreadTest_ManagedThreadId
932 MBRO mbro = new MBRO ();
934 class MBRO : MarshalByRefObject {
941 public string message;
945 public void ManagedThreadId_AppDomains ()
947 AppDomain currentDomain = AppDomain.CurrentDomain;
948 ad1 = AppDomain.CreateDomain ("AppDomain 1", currentDomain.Evidence, currentDomain.SetupInformation);
949 ad2 = AppDomain.CreateDomain ("AppDomain 2", currentDomain.Evidence, currentDomain.SetupInformation);
951 Thread a = new Thread (ThreadA);
952 Thread b = new Thread (ThreadB);
953 // execute on AppDomain 1 thread A
954 // execute on AppDomain 2 thread B
955 // execute on AppDomain 1 thread B - must have same ManagedThreadId as Ad 2 on thread B
961 AppDomain.Unload (ad1);
962 AppDomain.Unload (ad2);
964 if (mbro.message != null)
965 Assert.Fail (mbro.message);
967 // 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);
969 Assert.AreEqual ("AppDomain 1", mbro.ad_a1, "Name #1");
970 Assert.AreEqual ("AppDomain 1", mbro.ad_b1, "Name #2");
971 Assert.AreEqual ("AppDomain 2", mbro.ad_b2, "Name #3");
973 Assert.AreNotEqual (mbro.id_a1, mbro.id_b1, "Id #1");
974 Assert.AreNotEqual (mbro.id_a1, mbro.id_b2, "Id #2");
975 Assert.AreEqual (mbro.id_b1, mbro.id_b2, "Id #3");
977 Assert.AreNotEqual (mbro.id_a1, Thread.CurrentThread.ManagedThreadId, "Id #4");
978 Assert.AreNotEqual (mbro.id_b1, Thread.CurrentThread.ManagedThreadId, "Id #5");
979 Assert.AreNotEqual (mbro.id_b2, Thread.CurrentThread.ManagedThreadId, "Id #6");
980 Assert.AreNotEqual (mbro.ad_a1, AppDomain.CurrentDomain.FriendlyName, "Name #4");
981 Assert.AreNotEqual (mbro.ad_b1, AppDomain.CurrentDomain.FriendlyName, "Name #5");
982 Assert.AreNotEqual (mbro.ad_b2, AppDomain.CurrentDomain.FriendlyName, "Name #6");
987 mbro.id_a1 = Thread.CurrentThread.ManagedThreadId;
988 mbro.ad_a1 = AppDomain.CurrentDomain.FriendlyName;
993 mbro.id_b2 = Thread.CurrentThread.ManagedThreadId;
994 mbro.ad_b2 = AppDomain.CurrentDomain.FriendlyName;
999 mbro.id_b1 = Thread.CurrentThread.ManagedThreadId;
1000 mbro.ad_b1 = AppDomain.CurrentDomain.FriendlyName;
1003 void ThreadA (object obj)
1005 // Console.WriteLine ("ThreadA");
1007 ad1.DoCallBack (A1);
1008 } catch (Exception ex) {
1009 mbro.message = string.Format ("ThreadA exception: {0}", ex);
1011 // Console.WriteLine ("ThreadA Done");
1014 void ThreadB (object obj)
1016 // Console.WriteLine ("ThreadB");
1018 ad2.DoCallBack (B2);
1019 ad1.DoCallBack (B1);
1020 } catch (Exception ex) {
1021 mbro.message = string.Format ("ThreadB exception: {0}", ex);
1023 // Console.WriteLine ("ThreadB Done");
1028 public class ThreadApartmentTest
1034 [Test] // bug #81658
1035 public void ApartmentState_StoppedThread ()
1037 Thread t1 = new Thread (new ThreadStart (Start));
1041 ApartmentState state = t1.ApartmentState;
1042 Assert.Fail ("#A1: " + state.ToString ());
1043 } catch (ThreadStateException ex) {
1044 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A2");
1045 Assert.IsNull (ex.InnerException, "#A3");
1046 Assert.IsNotNull (ex.Message, "#A4");
1049 Thread t2 = new Thread (new ThreadStart (Start));
1050 t2.IsBackground = true;
1054 ApartmentState state = t2.ApartmentState;
1055 Assert.Fail ("#B1: " + state.ToString ());
1056 } catch (ThreadStateException ex) {
1057 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B2");
1058 Assert.IsNull (ex.InnerException, "#B3");
1059 Assert.IsNotNull (ex.Message, "#B4");
1064 public void ApartmentState_BackGround ()
1066 Thread t1 = new Thread (new ThreadStart (Start));
1067 t1.IsBackground = true;
1068 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "#1");
1069 t1.ApartmentState = ApartmentState.STA;
1070 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#2");
1074 public void TestApartmentState ()
1076 Thread t1 = new Thread (new ThreadStart (Start));
1077 Thread t2 = new Thread (new ThreadStart (Start));
1078 Thread t3 = new Thread (new ThreadStart (Start));
1080 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "Thread1 Default");
1081 Assert.AreEqual (ApartmentState.Unknown, t2.ApartmentState, "Thread2 Default");
1082 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Default");
1084 t1.ApartmentState = ApartmentState.STA;
1085 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1086 t1.ApartmentState = ApartmentState.MTA;
1087 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Twice");
1089 t2.ApartmentState = ApartmentState.MTA;
1090 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Once");
1091 t2.ApartmentState = ApartmentState.STA;
1092 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Twice");
1094 bool exception_occured = false;
1096 t3.ApartmentState = ApartmentState.Unknown;
1099 exception_occured = true;
1101 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Set Invalid");
1103 Assert.IsFalse (exception_occured, "Thread3 Set Invalid Exception Occured");
1105 Assert.IsTrue (exception_occured, "Thread3 Set Invalid Exception Occured");
1109 exception_occured = false;
1111 t1.ApartmentState = ApartmentState.STA;
1114 exception_occured = true;
1116 Assert.IsTrue (exception_occured, "Thread1 Started Invalid Exception Occured");
1120 public void Volatile () {
1122 Thread.VolatileWrite (ref v3, double.MaxValue);
1123 Assert.AreEqual (v3, double.MaxValue);
1126 Thread.VolatileWrite (ref v4, float.MaxValue);
1127 Assert.AreEqual (v4, float.MaxValue);
1131 public void SetNameTpThread () {
1132 ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
1135 static void ThreadProc(Object stateInfo) {
1136 Thread.CurrentThread.Name = "My Worker";
1140 public class TestUtil
1142 public static void WaitForNotAlive (Thread t, string s)
1144 WhileAlive (t, true, s);
1147 public static void WaitForAlive (Thread t, string s)
1149 WhileAlive (t, false, s);
1152 public static bool WaitForAliveOrStop (Thread t, string s)
1154 return WhileAliveOrStop (t, false, s);
1157 public static void WhileAlive (Thread t, bool alive, string s)
1159 DateTime ti = DateTime.Now;
1160 while (t.IsAlive == alive) {
1161 if ((DateTime.Now - ti).TotalSeconds > 10) {
1162 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1163 else Assert.Fail ("Timeout while waiting for alive state. " + s);
1168 public static bool WhileAliveOrStop (Thread t, bool alive, string s)
1170 DateTime ti = DateTime.Now;
1171 while (t.IsAlive == alive) {
1172 if (t.ThreadState == ThreadState.Stopped)
1175 if ((DateTime.Now - ti).TotalSeconds > 10) {
1176 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1177 else Assert.Fail ("Timeout while waiting for alive state. " + s);