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 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.NoPrincipal);
29 IPrincipal p = Thread.CurrentPrincipal;
30 Assert.IsNull (p, "#1");
32 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
33 Assert.IsNotNull (Thread.CurrentPrincipal, "#2");
35 Thread.CurrentPrincipal = null;
36 Assert.IsNull (Thread.CurrentPrincipal, "#3");
37 // in this case we can return to null
40 public static void UnauthenticatedPrincipal ()
42 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.UnauthenticatedPrincipal);
43 IPrincipal p = Thread.CurrentPrincipal;
44 Assert.IsNotNull (p, "#1");
45 Assert.IsTrue ((p is GenericPrincipal), "#2");
46 Assert.AreEqual (String.Empty, p.Identity.Name, "#3");
47 Assert.AreEqual (String.Empty, p.Identity.AuthenticationType, "#4");
48 Assert.IsFalse (p.Identity.IsAuthenticated, "#5");
50 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
51 Assert.IsNotNull (Thread.CurrentPrincipal, "#6");
53 Thread.CurrentPrincipal = null;
54 Assert.IsNotNull (Thread.CurrentPrincipal, "#7");
55 // in this case we can't return to null
58 public static void WindowsPrincipal ()
60 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.WindowsPrincipal);
61 IPrincipal p = Thread.CurrentPrincipal;
62 Assert.IsNotNull (p, "#1");
63 Assert.IsTrue ((p is WindowsPrincipal), "#2");
64 Assert.IsNotNull (p.Identity.Name, "#3");
65 Assert.IsNotNull (p.Identity.AuthenticationType, "#4");
66 Assert.IsTrue (p.Identity.IsAuthenticated, "#5");
68 // note: we can switch from a WindowsPrincipal to a GenericPrincipal
69 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
70 Assert.IsNotNull (Thread.CurrentPrincipal, "#6");
72 Thread.CurrentPrincipal = null;
73 Assert.IsNotNull (Thread.CurrentPrincipal, "#7");
74 // in this case we can't return to null
77 public static void CopyOnNewThread ()
79 Assert.IsNotNull (Thread.CurrentPrincipal, "#1");
80 Assert.AreEqual ("good", Thread.CurrentPrincipal.Identity.Name, "#2");
85 [Category("MobileNotWorking")] // Abort #10240
86 public class ThreadTest
88 //TimeSpan Infinite = new TimeSpan (-10000); // -10000 ticks == -1 ms
89 TimeSpan SmallNegative = new TimeSpan (-2); // between 0 and -1.0 (infinite) ms
90 TimeSpan Negative = new TimeSpan (-20000); // really negative
91 //TimeSpan MaxValue = TimeSpan.FromMilliseconds ((long) Int32.MaxValue);
92 TimeSpan TooLarge = TimeSpan.FromMilliseconds ((long) Int32.MaxValue + 1);
99 switch (Environment.OSVersion.Platform) {
100 case PlatformID.Win32NT:
101 case PlatformID.Win32S:
102 case PlatformID.Win32Windows:
103 case PlatformID.WinCE:
108 // check a class in mscorlib to determine if we're running on Mono
109 if (Type.GetType ("System.MonoType", false) != null)
113 //Some Classes to test as threads
117 public Thread thread1;
123 thread1 = (Thread)null;
125 endm1 = endm2 = false;
128 public void TestMethod()
136 public void TestMethod2()
138 if (!(thread1==(Thread)null) )
149 public bool run = false;
156 public void TestMethod()
171 public C1Test sub_class;
172 public Thread sub_thread;
176 sub_class = new C1Test();
177 sub_thread = new Thread(new ThreadStart(sub_class.TestMethod));
180 public void TestMethod1()
190 public C1Test class1;
191 public C1Test class2;
192 public Thread thread1;
193 public Thread thread2;
201 class1 = new C1Test();
202 class2 = new C1Test();
203 thread1 = new Thread(new ThreadStart(class1.TestMethod));
204 thread2 = new Thread(new ThreadStart(class2.TestMethod));
207 public void TestMethod1()
210 TestUtil.WaitForAlive (thread1, "wait1");
213 TestUtil.WaitForAlive (thread2, "wait2");
216 TestUtil.WaitForNotAlive (thread1, "wait3");
219 TestUtil.WaitForNotAlive (thread2, "wait4");
223 public void TestMethod2()
231 public void TestCtor1()
233 C1Test test1 = new C1Test();
234 Thread t = new Thread (new ThreadStart (test1.TestMethod));
236 Assert.IsTrue (t.CurrentCulture.IsReadOnly, "CurrentCulture.IsReadOnly");
237 Assert.IsFalse (t.IsAlive, "IsAlive");
238 Assert.IsFalse (t.IsBackground, "IsBackground");
239 Assert.IsNull (t.Name, "Name");
240 Assert.AreEqual (ThreadState.Unstarted, t.ThreadState, "ThreadState");
244 [Category ("NotWorking")] // we're not sharing (read-only) CultureInfo
245 public void CultureInfo_Shared_Across_Threads ()
247 Thread t = new Thread (TestCtor1);
248 Assert.AreSame (t.CurrentCulture, t.CurrentUICulture, "Culture");
250 Assert.AreSame (t.CurrentCulture, CultureInfo.CurrentCulture, "CultureInfo.CurrentCulture");
251 Assert.AreSame (t.CurrentUICulture, CultureInfo.CurrentUICulture, "CultureInfo.CurrentUICulture");
253 Assert.AreSame (t.CurrentCulture, Thread.CurrentThread.CurrentCulture, "Thread.CurrentThread.CurrentCulture");
254 Assert.AreSame (t.CurrentUICulture, Thread.CurrentThread.CurrentUICulture, "Thread.CurrentThread.CurrentUICulture");
257 [Test] // bug #325566
258 public void GetHashCodeTest ()
260 C1Test test1 = new C1Test ();
261 Thread tA = new Thread (new ThreadStart (test1.TestMethod));
262 int hA1 = tA.GetHashCode ();
264 Assert.IsTrue (hA1 > 0, "#A1");
267 int hA2 = tA.GetHashCode ();
268 Assert.AreEqual (hA1, hA2, "#A2");
270 int hA3 = tA.GetHashCode ();
271 Assert.AreEqual (hA1, hA3, "#A3");
273 Assert.AreEqual (hA1, tA.ManagedThreadId, "#A4");
276 test1 = new C1Test ();
277 Thread tB = new Thread (new ThreadStart (test1.TestMethod));
278 int hB1 = tB.GetHashCode ();
280 Assert.IsTrue (hB1 > 0, "#B1");
283 int hB2 = tB.GetHashCode ();
284 Assert.AreEqual (hB1, hB2, "#B2");
286 int hB3 = tB.GetHashCode ();
287 Assert.AreEqual (hB1, hB3, "#B3");
289 Assert.AreEqual (hB1, tB.ManagedThreadId, "#B4");
291 Assert.IsFalse (hA2 == hB2, "#B5");
296 public void ManagedThreadId ()
298 C1Test test1 = new C1Test ();
299 Thread t1 = new Thread (new ThreadStart (test1.TestMethod));
300 int mtA1 = t1.ManagedThreadId;
302 int mtA2 = t1.ManagedThreadId;
304 int mtA3 = t1.ManagedThreadId;
305 Assert.AreEqual (mtA1, mtA2, "#A1");
306 Assert.AreEqual (mtA2, mtA3, "#A2");
308 test1 = new C1Test ();
309 Thread t2 = new Thread (new ThreadStart (test1.TestMethod));
310 int mtB1 = t2.ManagedThreadId;
312 int mtB2 = t2.ManagedThreadId;
314 int mtB3 = t2.ManagedThreadId;
315 Assert.AreEqual (mtB1, mtB2, "#B1");
316 Assert.AreEqual (mtB2, mtB3, "#B2");
317 Assert.IsFalse (mtB1 == mtA1, "#B3");
322 [Category ("NotDotNet")] // it hangs.
323 public void TestStart()
325 if (is_win32 && is_mono)
326 Assert.Fail ("This test fails on Win32. The test should be fixed.");
328 C1Test test1 = new C1Test();
329 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
332 Assert.AreEqual (10, test1.cnt, "#1");
335 C2Test test1 = new C2Test();
336 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
342 } catch (ThreadStateException) {
346 C2Test test1 = new C2Test();
347 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
351 bool started = (TestThread.ThreadState == ThreadState.Running);
352 Assert.AreEqual (started, test1.run, "#15 Thread Is not in the correct state: ");
358 public void TestApartmentState ()
360 if (is_win32 && is_mono)
361 Assert.Fail ("This test fails on mono on win32. Our runtime should be fixed.");
363 C2Test test1 = new C2Test();
364 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
365 Assert.AreEqual (ApartmentState.Unknown, TestThread.ApartmentState, "#1");
367 TestUtil.WaitForAlive (TestThread, "wait5");
369 Assert.AreEqual (ApartmentState.MTA, TestThread.ApartmentState, "#2");
371 Assert.AreEqual (ApartmentState.Unknown, TestThread.ApartmentState, "#3");
377 public void TestPriority1()
379 if (is_win32 && is_mono)
380 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
382 C2Test test1 = new C2Test();
383 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
385 TestThread.Priority=ThreadPriority.BelowNormal;
386 ThreadPriority after = TestThread.Priority;
388 TestUtil.WaitForAlive (TestThread, "wait7");
389 ThreadPriority before = TestThread.Priority;
390 Assert.AreEqual (before, after, "#41 Unexpected Priority Change: ");
397 [Category ("NotDotNet")] // on MS, Thread is still in AbortRequested state when Start is invoked
398 public void AbortUnstarted ()
400 C2Test test1 = new C2Test();
401 Thread th = new Thread (new ThreadStart (test1.TestMethod));
407 [Category ("NotDotNet")] // on MS, ThreadState is immediately Stopped after Abort
408 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
409 public void TestPriority2()
411 C2Test test1 = new C2Test();
412 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
414 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#42 Incorrect Priority in New thread: ");
416 TestUtil.WaitForAliveOrStop (TestThread, "wait8");
417 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#43 Incorrect Priority in Started thread: ");
421 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#44 Incorrect Priority in Aborted thread: ");
425 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
426 public void TestPriority3()
428 C2Test test1 = new C2Test();
429 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
432 TestThread.Priority = ThreadPriority.Lowest;
433 Assert.AreEqual (ThreadPriority.Lowest, TestThread.Priority, "#45A Incorrect Priority:");
434 TestThread.Priority = ThreadPriority.BelowNormal;
435 Assert.AreEqual (ThreadPriority.BelowNormal, TestThread.Priority, "#45B Incorrect Priority:");
436 TestThread.Priority = ThreadPriority.Normal;
437 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#45C Incorrect Priority:");
438 TestThread.Priority = ThreadPriority.AboveNormal;
439 Assert.AreEqual (ThreadPriority.AboveNormal, TestThread.Priority, "#45D Incorrect Priority:");
440 TestThread.Priority = ThreadPriority.Highest;
441 Assert.AreEqual (ThreadPriority.Highest, TestThread.Priority, "#45E Incorrect Priority:");
449 public void TestUndivisibleByPageSizeMaxStackSize ()
451 const int undivisible_stacksize = 1048573;
453 var thread = new Thread (new ThreadStart (delegate {}), undivisible_stacksize);
459 public void TestIsBackground1 ()
461 if (is_win32 && is_mono)
462 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
464 C2Test test1 = new C2Test();
465 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
468 TestUtil.WaitForAlive (TestThread, "wait9");
469 bool state = TestThread.IsBackground;
470 Assert.IsFalse (state, "#51 IsBackground not set at the default state: ");
477 public void TestIsBackground2 ()
479 C2Test test1 = new C2Test();
480 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
481 TestThread.IsBackground = true;
488 if (TestThread.IsAlive) {
490 Assert.IsTrue (TestThread.IsBackground, "#52 Is Background Changed to Start ");
491 } catch (ThreadStateException) {
492 // Ignore if thread died meantime
498 public void TestName()
500 if (is_win32 && is_mono)
501 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
503 C2Test test1 = new C2Test();
504 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
507 TestUtil.WaitForAlive (TestThread, "wait10");
508 string name = TestThread.Name;
509 Assert.IsNull (name, "#61 Name set when mustn't be set: ");
510 string newname = "Testing....";
511 TestThread.Name = newname;
512 Assert.AreEqual (newname, TestThread.Name, "#62 Name not set when must be set: ");
521 Thread t = new Thread (new ThreadStart (Name));
522 Assert.IsNull (t.Name, "Name-1");
524 Assert.IsNull (t.Name, "Name-2");
528 [ExpectedException (typeof (InvalidOperationException))]
529 public void Rename ()
531 Thread t = new Thread (new ThreadStart (Rename));
536 bool rename_finished;
540 public void RenameTpThread ()
542 object monitor = new object ();
543 ThreadPool.QueueUserWorkItem (new WaitCallback (Rename_callback), monitor);
545 if (!rename_finished)
546 Monitor.Wait (monitor);
548 Assert.IsTrue (rename_failed);
551 void Rename_callback (object o) {
552 Thread.CurrentThread.Name = "a";
554 Thread.CurrentThread.Name = "b";
555 Console.WriteLine ("Thread name is: {0}", Thread.CurrentThread.Name);
556 } catch (Exception e) {
557 Console.Error.WriteLine (e);
558 rename_failed = true;
562 rename_finished = true;
563 Monitor.Pulse (monitor);
568 public void TestNestedThreads1()
570 C3Test test1 = new C3Test();
571 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
574 TestUtil.WaitForAlive (TestThread, "wait11");
581 public void TestNestedThreads2()
583 C4Test test1 = new C4Test();
584 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
593 public void TestJoin1()
595 C1Test test1 = new C1Test();
596 C1Test test2 = new C1Test();
597 Thread thread1 = new Thread(new ThreadStart(test1.TestMethod));
598 Thread thread2 = new Thread(new ThreadStart(test1.TestMethod2));
610 [ExpectedException (typeof (ArgumentOutOfRangeException))]
611 public void Join_Int32_Negative ()
613 // -1 is Timeout.Infinite
614 Thread.CurrentThread.Join (-2);
618 [ExpectedException (typeof (ArgumentOutOfRangeException))]
619 public void Join_TimeSpan_Negative ()
621 Thread.CurrentThread.Join (Negative);
625 [ExpectedException (typeof (ArgumentOutOfRangeException))]
626 public void Join_TimeSpan_TooLarge ()
628 Thread.CurrentThread.Join (TooLarge);
632 public void Join_TimeSpan_SmallNegative ()
634 Thread.CurrentThread.Join (SmallNegative);
638 [ExpectedException (typeof (ArgumentOutOfRangeException))]
639 public void Sleep_Int32_Negative ()
641 // -1 is Timeout.Infinite
646 public void Sleep_TimeSpan_SmallNegative ()
648 Thread.Sleep (SmallNegative);
652 [ExpectedException (typeof (ArgumentOutOfRangeException))]
653 public void Sleep_TimeSpan_Negative ()
655 Thread.Sleep (Negative);
659 [ExpectedException (typeof (ArgumentOutOfRangeException))]
660 public void Sleep_TimeSpan_TooLarge ()
662 Thread.Sleep (TooLarge);
666 public void SpinWait ()
668 // no exception for negative numbers
669 Thread.SpinWait (Int32.MinValue);
674 public void TestThreadState ()
676 if (is_win32 && is_mono)
677 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
679 //TODO: Test The rest of the possible transitions
680 C2Test test1 = new C2Test();
681 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
682 Assert.AreEqual (ThreadState.Unstarted, TestThread.ThreadState, "#101 Wrong Thread State");
685 //while(!TestThread.IsAlive); //In the MS Documentation this is not necessary
686 //but in the MS SDK it is
687 Assert.IsTrue (TestThread.ThreadState == ThreadState.Running || (TestThread.ThreadState & ThreadState.Unstarted) != 0,
688 "#102 Wrong Thread State: " + TestThread.ThreadState.ToString ());
693 TestUtil.WaitForNotAlive (TestThread, "wait12");
694 // Docs say state will be Stopped, but Aborted happens sometimes (?)
695 Assert.IsTrue ((ThreadState.Stopped & TestThread.ThreadState) != 0 || (ThreadState.Aborted & TestThread.ThreadState) != 0,
696 "#103 Wrong Thread State: " + TestThread.ThreadState.ToString ());
700 [Ignore ("see comment below.")]
701 public void CurrentPrincipal_PrincipalPolicy_NoPrincipal ()
703 // note: switching from PrincipalPolicy won't work inside the same thread
704 // because as soon as a Principal object is created the Policy doesn't matter anymore
705 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.NoPrincipal));
715 [Ignore ("see comment below.")]
716 public void CurrentPrincipal_PrincipalPolicy_UnauthenticatedPrincipal ()
718 // note: switching from PrincipalPolicy won't work inside the same thread
719 // because as soon as a Principal object is created the Policy doesn't matter anymore
720 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.UnauthenticatedPrincipal));
730 public void CurrentPrincipal_PrincipalPolicy_WindowsPrincipal ()
732 // note: switching from PrincipalPolicy won't work inside the same thread
733 // because as soon as a Principal object is created the Policy doesn't matter anymore
734 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.WindowsPrincipal));
744 public void IPrincipal_CopyOnNewThread ()
746 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("bad"), null);
747 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.CopyOnNewThread));
749 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("good"), null);
760 public void TestSuspend ()
762 Thread t = new Thread (new ThreadStart (DoCount));
763 t.IsBackground = true;
766 CheckIsRunning ("t1", t);
769 WaitSuspended ("t2", t);
771 CheckIsNotRunning ("t3", t);
774 WaitResumed ("t4", t);
776 CheckIsRunning ("t5", t);
779 TestUtil.WaitForNotAlive (t, "wait13");
780 CheckIsNotRunning ("t6", t);
784 [Category("NotDotNet")] // On MS, ThreadStateException is thrown on Abort: "Thread is suspended; attempting to abort"
785 public void TestSuspendAbort ()
787 if (is_win32 && is_mono)
788 Assert.Fail ("This test fails on Win32. The test should be fixed.");
790 Thread t = new Thread (new ThreadStart (DoCount));
791 t.IsBackground = true;
794 CheckIsRunning ("t1", t);
797 WaitSuspended ("t2", t);
799 CheckIsNotRunning ("t3", t);
804 while (t.IsAlive && n < 200) {
809 Assert.IsTrue (n < 200, "Timeout while waiting for abort");
811 CheckIsNotRunning ("t6", t);
815 public void Test_Interrupt ()
817 bool interruptedExceptionThrown = false;
818 ThreadPool.QueueUserWorkItem (Test_Interrupt_Worker, Thread.CurrentThread);
826 } catch (ThreadInterruptedException) {
827 Assert.Fail ("ThreadInterruptedException thrown twice");
830 } catch (ThreadInterruptedException) {
831 interruptedExceptionThrown = true;
834 Assert.IsTrue (interruptedExceptionThrown, "ThreadInterruptedException expected.");
838 [ExpectedException (typeof (ArgumentNullException))]
839 public void TestQueueUserWorkItemNullCallback ()
841 ThreadPool.QueueUserWorkItem (null, null);
844 private void Test_Interrupt_Worker (object o)
846 Thread t = o as Thread;
852 [Category ("NotDotNet")] // it crashes nunit.
853 public void Test_InterruptCurrentThread ()
855 bool interruptedExceptionThrown = false;
857 Thread.CurrentThread.Interrupt ();
861 } catch (ThreadInterruptedException) {
866 public void GetNamedDataSlotTest ()
868 Assert.IsNotNull (Thread.GetNamedDataSlot ("te#st"), "#1");
869 Assert.AreSame (Thread.GetNamedDataSlot ("te#st"), Thread.GetNamedDataSlot ("te#st"), "#2");
872 void CheckIsRunning (string s, Thread t)
876 Assert.IsTrue (counter > c, s);
879 void CheckIsNotRunning (string s, Thread t)
883 Assert.AreEqual (counter, c, s);
886 void WaitSuspended (string s, Thread t)
889 ThreadState state = t.ThreadState;
890 while ((state & ThreadState.Suspended) == 0) {
891 Assert.IsTrue ((state & ThreadState.SuspendRequested) != 0, s + ": expected SuspendRequested state");
894 Assert.IsTrue (n < 100, s + ": failed to suspend");
895 state = t.ThreadState;
897 Assert.IsTrue ((state & ThreadState.SuspendRequested) == 0, s + ": SuspendRequested state not expected");
900 void WaitResumed (string s, Thread t)
903 while ((t.ThreadState & ThreadState.Suspended) != 0) {
906 Assert.IsTrue (n < 100, s + ": failed to resume");
910 public void DoCount ()
920 public class ThreadStateTest {
926 public void IsBackGround ()
928 Thread t1 = new Thread (new ThreadStart (Start));
929 Assert.AreEqual (ThreadState.Unstarted, t1.ThreadState, "#A1");
930 Assert.IsFalse (t1.IsBackground, "#A2");
933 Assert.AreEqual (ThreadState.Stopped, t1.ThreadState, "#A3");
936 bool isBackGround = t1.IsBackground;
937 Assert.Fail ("#A4: " + isBackGround.ToString ());
938 } catch (ThreadStateException ex) {
939 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A5");
940 Assert.IsNull (ex.InnerException, "#A6");
941 Assert.IsNotNull (ex.Message, "#A7");
944 Thread t2 = new Thread (new ThreadStart (Start));
945 Assert.AreEqual (ThreadState.Unstarted, t2.ThreadState, "#B1");
946 t2.IsBackground = true;
947 Assert.AreEqual (ThreadState.Unstarted | ThreadState.Background, t2.ThreadState, "#B2");
948 Assert.IsTrue (t2.IsBackground, "#B3");
951 Assert.AreEqual (ThreadState.Stopped, t2.ThreadState, "#B4");
954 bool isBackGround = t2.IsBackground;
955 Assert.Fail ("#B5: " + isBackGround.ToString ());
956 } catch (ThreadStateException ex) {
957 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B6");
958 Assert.IsNull (ex.InnerException, "#B7");
959 Assert.IsNotNull (ex.Message, "#B8");
966 public class ThreadTest_ManagedThreadId
970 MBRO mbro = new MBRO ();
972 class MBRO : MarshalByRefObject {
979 public string message;
983 public void ManagedThreadId_AppDomains ()
985 AppDomain currentDomain = AppDomain.CurrentDomain;
986 ad1 = AppDomain.CreateDomain ("AppDomain 1", currentDomain.Evidence, currentDomain.SetupInformation);
987 ad2 = AppDomain.CreateDomain ("AppDomain 2", currentDomain.Evidence, currentDomain.SetupInformation);
989 Thread a = new Thread (ThreadA);
990 Thread b = new Thread (ThreadB);
991 // execute on AppDomain 1 thread A
992 // execute on AppDomain 2 thread B
993 // execute on AppDomain 1 thread B - must have same ManagedThreadId as Ad 2 on thread B
999 AppDomain.Unload (ad1);
1000 AppDomain.Unload (ad2);
1002 if (mbro.message != null)
1003 Assert.Fail (mbro.message);
1005 // 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);
1007 Assert.AreEqual ("AppDomain 1", mbro.ad_a1, "Name #1");
1008 Assert.AreEqual ("AppDomain 1", mbro.ad_b1, "Name #2");
1009 Assert.AreEqual ("AppDomain 2", mbro.ad_b2, "Name #3");
1011 Assert.AreNotEqual (mbro.id_a1, mbro.id_b1, "Id #1");
1012 Assert.AreNotEqual (mbro.id_a1, mbro.id_b2, "Id #2");
1013 Assert.AreEqual (mbro.id_b1, mbro.id_b2, "Id #3");
1015 Assert.AreNotEqual (mbro.id_a1, Thread.CurrentThread.ManagedThreadId, "Id #4");
1016 Assert.AreNotEqual (mbro.id_b1, Thread.CurrentThread.ManagedThreadId, "Id #5");
1017 Assert.AreNotEqual (mbro.id_b2, Thread.CurrentThread.ManagedThreadId, "Id #6");
1018 Assert.AreNotEqual (mbro.ad_a1, AppDomain.CurrentDomain.FriendlyName, "Name #4");
1019 Assert.AreNotEqual (mbro.ad_b1, AppDomain.CurrentDomain.FriendlyName, "Name #5");
1020 Assert.AreNotEqual (mbro.ad_b2, AppDomain.CurrentDomain.FriendlyName, "Name #6");
1025 mbro.id_a1 = Thread.CurrentThread.ManagedThreadId;
1026 mbro.ad_a1 = AppDomain.CurrentDomain.FriendlyName;
1031 mbro.id_b2 = Thread.CurrentThread.ManagedThreadId;
1032 mbro.ad_b2 = AppDomain.CurrentDomain.FriendlyName;
1037 mbro.id_b1 = Thread.CurrentThread.ManagedThreadId;
1038 mbro.ad_b1 = AppDomain.CurrentDomain.FriendlyName;
1041 void ThreadA (object obj)
1043 // Console.WriteLine ("ThreadA");
1045 ad1.DoCallBack (A1);
1046 } catch (Exception ex) {
1047 mbro.message = string.Format ("ThreadA exception: {0}", ex);
1049 // Console.WriteLine ("ThreadA Done");
1052 void ThreadB (object obj)
1054 // Console.WriteLine ("ThreadB");
1056 ad2.DoCallBack (B2);
1057 ad1.DoCallBack (B1);
1058 } catch (Exception ex) {
1059 mbro.message = string.Format ("ThreadB exception: {0}", ex);
1061 // Console.WriteLine ("ThreadB Done");
1066 public class ThreadApartmentTest
1072 [Test] // bug #81658
1073 public void ApartmentState_StoppedThread ()
1075 Thread t1 = new Thread (new ThreadStart (Start));
1079 ApartmentState state = t1.ApartmentState;
1080 Assert.Fail ("#A1: " + state.ToString ());
1081 } catch (ThreadStateException ex) {
1082 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A2");
1083 Assert.IsNull (ex.InnerException, "#A3");
1084 Assert.IsNotNull (ex.Message, "#A4");
1087 Thread t2 = new Thread (new ThreadStart (Start));
1088 t2.IsBackground = true;
1092 ApartmentState state = t2.ApartmentState;
1093 Assert.Fail ("#B1: " + state.ToString ());
1094 } catch (ThreadStateException ex) {
1095 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B2");
1096 Assert.IsNull (ex.InnerException, "#B3");
1097 Assert.IsNotNull (ex.Message, "#B4");
1102 public void ApartmentState_BackGround ()
1104 Thread t1 = new Thread (new ThreadStart (Start));
1105 t1.IsBackground = true;
1106 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "#1");
1107 t1.ApartmentState = ApartmentState.STA;
1108 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#2");
1112 public void TestApartmentState ()
1114 Thread t1 = new Thread (new ThreadStart (Start));
1115 Thread t2 = new Thread (new ThreadStart (Start));
1116 Thread t3 = new Thread (new ThreadStart (Start));
1118 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "Thread1 Default");
1119 Assert.AreEqual (ApartmentState.Unknown, t2.ApartmentState, "Thread2 Default");
1120 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Default");
1122 t1.ApartmentState = ApartmentState.STA;
1123 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1124 t1.ApartmentState = ApartmentState.MTA;
1125 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Twice");
1127 t2.ApartmentState = ApartmentState.MTA;
1128 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Once");
1129 t2.ApartmentState = ApartmentState.STA;
1130 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Twice");
1132 bool exception_occured = false;
1134 t3.ApartmentState = ApartmentState.Unknown;
1137 exception_occured = true;
1139 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Set Invalid");
1141 Assert.IsFalse (exception_occured, "Thread3 Set Invalid Exception Occured");
1143 Assert.IsTrue (exception_occured, "Thread3 Set Invalid Exception Occured");
1147 exception_occured = false;
1149 t1.ApartmentState = ApartmentState.STA;
1152 exception_occured = true;
1154 Assert.IsTrue (exception_occured, "Thread1 Started Invalid Exception Occured");
1158 public void TestSetApartmentStateSameState ()
1160 Thread t1 = new Thread (new ThreadStart (Start));
1161 t1.SetApartmentState (ApartmentState.STA);
1162 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1164 t1.SetApartmentState (ApartmentState.STA);
1165 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set twice");
1169 [ExpectedException(typeof(InvalidOperationException))]
1170 public void TestSetApartmentStateDiffState ()
1172 Thread t1 = new Thread (new ThreadStart (Start));
1173 t1.SetApartmentState (ApartmentState.STA);
1174 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1176 t1.SetApartmentState (ApartmentState.MTA);
1180 public void TestTrySetApartmentState ()
1182 Thread t1 = new Thread (new ThreadStart (Start));
1183 t1.SetApartmentState (ApartmentState.STA);
1184 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1186 bool result = t1.TrySetApartmentState (ApartmentState.MTA);
1187 Assert.IsFalse (result, "#2");
1189 result = t1.TrySetApartmentState (ApartmentState.STA);
1190 Assert.IsTrue (result, "#3");
1194 public void TestTrySetApartmentStateRunning ()
1196 Thread t1 = new Thread (new ThreadStart (Start));
1197 t1.SetApartmentState (ApartmentState.STA);
1198 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1203 t1.TrySetApartmentState (ApartmentState.STA);
1205 } catch (ThreadStateException) {
1212 public void Volatile () {
1214 Thread.VolatileWrite (ref v3, double.MaxValue);
1215 Assert.AreEqual (v3, double.MaxValue);
1218 Thread.VolatileWrite (ref v4, float.MaxValue);
1219 Assert.AreEqual (v4, float.MaxValue);
1223 public void Culture ()
1225 Assert.IsNotNull (Thread.CurrentThread.CurrentCulture, "CurrentCulture");
1226 Assert.IsNotNull (Thread.CurrentThread.CurrentUICulture, "CurrentUICulture");
1230 public void ThreadStartSimple ()
1233 Thread t = new Thread (delegate () {
1234 // ensure the NSAutoreleasePool works
1239 Assert.AreEqual (1, i, "ThreadStart");
1243 public void ParametrizedThreadStart ()
1247 Thread t = new Thread (delegate (object obj) {
1248 // ensure the NSAutoreleasePool works
1255 Assert.AreEqual (1, i, "ParametrizedThreadStart");
1256 Assert.AreEqual (this, arg, "obj");
1260 public void SetNameTpThread () {
1261 ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
1264 static void ThreadProc(Object stateInfo) {
1265 Thread.CurrentThread.Name = "My Worker";
1269 public class TestUtil
1271 public static void WaitForNotAlive (Thread t, string s)
1273 WhileAlive (t, true, s);
1276 public static void WaitForAlive (Thread t, string s)
1278 WhileAlive (t, false, s);
1281 public static bool WaitForAliveOrStop (Thread t, string s)
1283 return WhileAliveOrStop (t, false, s);
1286 public static void WhileAlive (Thread t, bool alive, string s)
1288 DateTime ti = DateTime.Now;
1289 while (t.IsAlive == alive) {
1290 if ((DateTime.Now - ti).TotalSeconds > 10) {
1291 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1292 else Assert.Fail ("Timeout while waiting for alive state. " + s);
1297 public static bool WhileAliveOrStop (Thread t, bool alive, string s)
1299 DateTime ti = DateTime.Now;
1300 while (t.IsAlive == alive) {
1301 if (t.ThreadState == ThreadState.Stopped)
1304 if ((DateTime.Now - ti).TotalSeconds > 10) {
1305 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1306 else Assert.Fail ("Timeout while waiting for alive state. " + s);