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.Threading.Tasks;
17 using System.Reflection;
18 using System.Collections.Generic;
19 using SD = System.Diagnostics;
21 using NUnit.Framework;
23 namespace MonoTests.System.Threading
25 // These tests seem to hang the 2.0 framework. So they are disabled for now
26 // Don't reenable them until you can run a few thousand times on an SMP box.
27 [Category ("NotWorking")]
28 public class ThreadedPrincipalTest
30 public static void NoPrincipal ()
32 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.NoPrincipal);
33 IPrincipal p = Thread.CurrentPrincipal;
34 Assert.IsNull (p, "#1");
36 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
37 Assert.IsNotNull (Thread.CurrentPrincipal, "#2");
39 Thread.CurrentPrincipal = null;
40 Assert.IsNull (Thread.CurrentPrincipal, "#3");
41 // in this case we can return to null
44 public static void UnauthenticatedPrincipal ()
46 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.UnauthenticatedPrincipal);
47 IPrincipal p = Thread.CurrentPrincipal;
48 Assert.IsNotNull (p, "#1");
49 Assert.IsTrue ((p is GenericPrincipal), "#2");
50 Assert.AreEqual (String.Empty, p.Identity.Name, "#3");
51 Assert.AreEqual (String.Empty, p.Identity.AuthenticationType, "#4");
52 Assert.IsFalse (p.Identity.IsAuthenticated, "#5");
54 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
55 Assert.IsNotNull (Thread.CurrentPrincipal, "#6");
57 Thread.CurrentPrincipal = null;
58 Assert.IsNotNull (Thread.CurrentPrincipal, "#7");
59 // in this case we can't return to null
62 public static void WindowsPrincipal ()
64 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.WindowsPrincipal);
65 IPrincipal p = Thread.CurrentPrincipal;
66 Assert.IsNotNull (p, "#1");
67 Assert.IsTrue ((p is WindowsPrincipal), "#2");
68 Assert.IsNotNull (p.Identity.Name, "#3");
69 Assert.IsNotNull (p.Identity.AuthenticationType, "#4");
70 Assert.IsTrue (p.Identity.IsAuthenticated, "#5");
72 // note: we can switch from a WindowsPrincipal to a GenericPrincipal
73 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
74 Assert.IsNotNull (Thread.CurrentPrincipal, "#6");
76 Thread.CurrentPrincipal = null;
77 Assert.IsNotNull (Thread.CurrentPrincipal, "#7");
78 // 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 [Category("MobileNotWorking")] // Abort #10240
90 public class ThreadTest
92 //TimeSpan Infinite = new TimeSpan (-10000); // -10000 ticks == -1 ms
93 TimeSpan SmallNegative = new TimeSpan (-2); // between 0 and -1.0 (infinite) ms
94 TimeSpan Negative = new TimeSpan (-20000); // really negative
95 //TimeSpan MaxValue = TimeSpan.FromMilliseconds ((long) Int32.MaxValue);
96 TimeSpan TooLarge = TimeSpan.FromMilliseconds ((long) Int32.MaxValue + 1);
98 //Some Classes to test as threads
102 public Thread thread1;
108 thread1 = (Thread)null;
110 endm1 = endm2 = false;
113 public void TestMethod()
121 public void TestMethod2()
123 if (!(thread1==(Thread)null) )
134 public bool run = false;
141 public void TestMethod()
156 public C1Test sub_class;
157 public Thread sub_thread;
161 sub_class = new C1Test();
162 sub_thread = new Thread(new ThreadStart(sub_class.TestMethod));
165 public void TestMethod1()
169 #if MONO_FEATURE_THREAD_ABORT
172 sub_thread.Interrupt ();
179 public C1Test class1;
180 public C1Test class2;
181 public Thread thread1;
182 public Thread thread2;
190 class1 = new C1Test();
191 class2 = new C1Test();
192 thread1 = new Thread(new ThreadStart(class1.TestMethod));
193 thread2 = new Thread(new ThreadStart(class2.TestMethod));
196 public void TestMethod1()
199 TestUtil.WaitForAlive (thread1, "wait1");
202 TestUtil.WaitForAlive (thread2, "wait2");
204 #if MONO_FEATURE_THREAD_ABORT
207 thread1.Interrupt ();
209 TestUtil.WaitForNotAlive (thread1, "wait3");
211 #if MONO_FEATURE_THREAD_ABORT
214 thread2.Interrupt ();
216 TestUtil.WaitForNotAlive (thread2, "wait4");
220 public void TestMethod2()
228 public void TestCtor1()
230 C1Test test1 = new C1Test();
231 Thread t = new Thread (new ThreadStart (test1.TestMethod));
233 Assert.IsTrue (t.CurrentCulture.IsReadOnly, "CurrentCulture.IsReadOnly");
234 Assert.IsFalse (t.IsAlive, "IsAlive");
235 Assert.IsFalse (t.IsBackground, "IsBackground");
236 Assert.IsNull (t.Name, "Name");
237 Assert.AreEqual (ThreadState.Unstarted, t.ThreadState, "ThreadState");
241 [Category ("NotWorking")] // we're not sharing (read-only) CultureInfo
242 public void CultureInfo_Shared_Across_Threads ()
244 Thread t = new Thread (TestCtor1);
245 Assert.AreSame (t.CurrentCulture, t.CurrentUICulture, "Culture");
247 Assert.AreSame (t.CurrentCulture, CultureInfo.CurrentCulture, "CultureInfo.CurrentCulture");
248 Assert.AreSame (t.CurrentUICulture, CultureInfo.CurrentUICulture, "CultureInfo.CurrentUICulture");
250 Assert.AreSame (t.CurrentCulture, Thread.CurrentThread.CurrentCulture, "Thread.CurrentThread.CurrentCulture");
251 Assert.AreSame (t.CurrentUICulture, Thread.CurrentThread.CurrentUICulture, "Thread.CurrentThread.CurrentUICulture");
254 [Test] // bug #325566
255 public void GetHashCodeTest ()
257 C1Test test1 = new C1Test ();
258 Thread tA = new Thread (new ThreadStart (test1.TestMethod));
259 int hA1 = tA.GetHashCode ();
260 Assert.IsTrue (hA1 > 0, "#A1");
262 int hA2 = tA.GetHashCode ();
263 Assert.AreEqual (hA1, hA2, "#A2");
265 int hA3 = tA.GetHashCode ();
266 Assert.AreEqual (hA1, hA3, "#A3");
267 Assert.AreEqual (hA1, tA.ManagedThreadId, "#A4");
269 test1 = new C1Test ();
270 Thread tB = new Thread (new ThreadStart (test1.TestMethod));
271 int hB1 = tB.GetHashCode ();
272 Assert.IsTrue (hB1 > 0, "#B1");
274 int hB2 = tB.GetHashCode ();
275 Assert.AreEqual (hB1, hB2, "#B2");
277 int hB3 = tB.GetHashCode ();
278 Assert.AreEqual (hB1, hB3, "#B3");
279 Assert.AreEqual (hB1, tB.ManagedThreadId, "#B4");
280 Assert.IsFalse (hA2 == hB2, "#B5");
284 public void ManagedThreadId ()
286 C1Test test1 = new C1Test ();
287 Thread t1 = new Thread (new ThreadStart (test1.TestMethod));
288 int mtA1 = t1.ManagedThreadId;
290 int mtA2 = t1.ManagedThreadId;
292 int mtA3 = t1.ManagedThreadId;
293 Assert.AreEqual (mtA1, mtA2, "#A1");
294 Assert.AreEqual (mtA2, mtA3, "#A2");
296 test1 = new C1Test ();
297 Thread t2 = new Thread (new ThreadStart (test1.TestMethod));
298 int mtB1 = t2.ManagedThreadId;
300 int mtB2 = t2.ManagedThreadId;
302 int mtB3 = t2.ManagedThreadId;
303 Assert.AreEqual (mtB1, mtB2, "#B1");
304 Assert.AreEqual (mtB2, mtB3, "#B2");
305 Assert.IsFalse (mtB1 == mtA1, "#B3");
309 [Category ("NotDotNet")] // it hangs.
310 public void TestStart()
313 C1Test test1 = new C1Test();
314 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
317 Assert.AreEqual (10, test1.cnt, "#1");
320 C2Test test1 = new C2Test();
321 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
323 #if MONO_FEATURE_THREAD_ABORT
326 TestThread.Interrupt ();
331 } catch (ThreadStateException) {
335 C2Test test1 = new C2Test();
336 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
340 bool started = (TestThread.ThreadState == ThreadState.Running);
341 Assert.AreEqual (started, test1.run, "#15 Thread Is not in the correct state: ");
342 #if MONO_FEATURE_THREAD_ABORT
345 TestThread.Interrupt ();
351 public void TestApartmentState ()
353 C2Test test1 = new C2Test();
354 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
355 Assert.AreEqual (ApartmentState.Unknown, TestThread.ApartmentState, "#1");
357 TestUtil.WaitForAlive (TestThread, "wait5");
358 Assert.AreEqual (ApartmentState.MTA, TestThread.ApartmentState, "#2");
359 #if MONO_FEATURE_THREAD_ABORT
362 TestThread.Interrupt ();
367 [Category ("NotWorking")] // setting the priority of a Thread before it is started isn't implemented in Mono yet
368 public void TestPriority1()
370 C2Test test1 = new C2Test();
371 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
373 TestThread.Priority=ThreadPriority.BelowNormal;
374 ThreadPriority before = TestThread.Priority;
375 Assert.AreEqual (ThreadPriority.BelowNormal, before, "#40 Unexpected priority before thread start: ");
377 TestUtil.WaitForAlive (TestThread, "wait7");
378 ThreadPriority after = TestThread.Priority;
379 Assert.AreEqual (before, after, "#41 Unexpected Priority Change: ");
381 #if MONO_FEATURE_THREAD_ABORT
384 TestThread.Interrupt ();
389 #if MONO_FEATURE_THREAD_ABORT
391 [Category ("NotDotNet")] // on MS, Thread is still in AbortRequested state when Start is invoked
392 public void AbortUnstarted ()
394 C2Test test1 = new C2Test();
395 Thread th = new Thread (new ThreadStart (test1.TestMethod));
402 [Category ("NotDotNet")] // on MS, ThreadState is immediately Stopped after Abort
403 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
404 public void TestPriority2()
406 C2Test test1 = new C2Test();
407 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
409 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#42 Incorrect Priority in New thread: ");
411 TestUtil.WaitForAliveOrStop (TestThread, "wait8");
412 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#43 Incorrect Priority in Started thread: ");
414 #if MONO_FEATURE_THREAD_ABORT
417 TestThread.Interrupt ();
420 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#44 Incorrect Priority in Aborted thread: ");
424 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
425 public void TestPriority3()
427 C2Test test1 = new C2Test();
428 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
431 TestThread.Priority = ThreadPriority.Lowest;
432 Assert.AreEqual (ThreadPriority.Lowest, TestThread.Priority, "#45A Incorrect Priority:");
433 TestThread.Priority = ThreadPriority.BelowNormal;
434 Assert.AreEqual (ThreadPriority.BelowNormal, TestThread.Priority, "#45B Incorrect Priority:");
435 TestThread.Priority = ThreadPriority.Normal;
436 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#45C Incorrect Priority:");
437 TestThread.Priority = ThreadPriority.AboveNormal;
438 Assert.AreEqual (ThreadPriority.AboveNormal, TestThread.Priority, "#45D Incorrect Priority:");
439 TestThread.Priority = ThreadPriority.Highest;
440 Assert.AreEqual (ThreadPriority.Highest, TestThread.Priority, "#45E Incorrect Priority:");
443 #if MONO_FEATURE_THREAD_ABORT
446 TestThread.Interrupt ();
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 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: ");
472 #if MONO_FEATURE_THREAD_ABORT
475 TestThread.Interrupt ();
481 public void TestIsBackground2 ()
483 C2Test test1 = new C2Test();
484 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
485 TestThread.IsBackground = true;
489 #if MONO_FEATURE_THREAD_ABORT
492 TestThread.Interrupt ();
496 if (TestThread.IsAlive) {
498 Assert.IsTrue (TestThread.IsBackground, "#52 Is Background Changed to Start ");
499 } catch (ThreadStateException) {
500 // Ignore if thread died meantime
506 public void TestName()
508 C2Test test1 = new C2Test();
509 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
512 TestUtil.WaitForAlive (TestThread, "wait10");
513 string name = TestThread.Name;
514 Assert.IsNull (name, "#61 Name set when mustn't be set: ");
515 string newname = "Testing....";
516 TestThread.Name = newname;
517 Assert.AreEqual (newname, TestThread.Name, "#62 Name not set when must be set: ");
519 #if MONO_FEATURE_THREAD_ABORT
522 TestThread.Interrupt ();
530 Thread t = new Thread (new ThreadStart (Name));
531 Assert.IsNull (t.Name, "Name-1");
533 Assert.IsNull (t.Name, "Name-2");
537 [ExpectedException (typeof (InvalidOperationException))]
538 public void Rename ()
540 Thread t = new Thread (new ThreadStart (Rename));
546 public void TestNestedThreads1()
548 C3Test test1 = new C3Test();
549 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
552 TestUtil.WaitForAlive (TestThread, "wait11");
554 #if MONO_FEATURE_THREAD_ABORT
557 TestThread.Interrupt ();
563 public void TestNestedThreads2()
565 C4Test test1 = new C4Test();
566 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
570 #if MONO_FEATURE_THREAD_ABORT
573 TestThread.Interrupt ();
579 public void TestJoin1()
581 C1Test test1 = new C1Test();
582 C1Test test2 = new C1Test();
583 Thread thread1 = new Thread(new ThreadStart(test1.TestMethod));
584 Thread thread2 = new Thread(new ThreadStart(test1.TestMethod2));
590 #if MONO_FEATURE_THREAD_ABORT
594 thread1.Interrupt ();
595 thread2.Interrupt ();
601 [ExpectedException (typeof (ArgumentOutOfRangeException))]
602 public void Join_Int32_Negative ()
604 // -1 is Timeout.Infinite
605 Thread.CurrentThread.Join (-2);
609 [ExpectedException (typeof (ArgumentOutOfRangeException))]
610 public void Join_TimeSpan_Negative ()
612 Thread.CurrentThread.Join (Negative);
616 [ExpectedException (typeof (ArgumentOutOfRangeException))]
617 public void Join_TimeSpan_TooLarge ()
619 Thread.CurrentThread.Join (TooLarge);
623 public void Join_TimeSpan_SmallNegative ()
625 Thread.CurrentThread.Join (SmallNegative);
629 [ExpectedException (typeof (ArgumentOutOfRangeException))]
630 public void Sleep_Int32_Negative ()
632 // -1 is Timeout.Infinite
637 public void Sleep_TimeSpan_SmallNegative ()
639 Thread.Sleep (SmallNegative);
643 [ExpectedException (typeof (ArgumentOutOfRangeException))]
644 public void Sleep_TimeSpan_Negative ()
646 Thread.Sleep (Negative);
650 [ExpectedException (typeof (ArgumentOutOfRangeException))]
651 public void Sleep_TimeSpan_TooLarge ()
653 Thread.Sleep (TooLarge);
657 public void SpinWait ()
659 // no exception for negative numbers
660 Thread.SpinWait (Int32.MinValue);
665 public void TestThreadState ()
667 //TODO: Test The rest of the possible transitions
668 C2Test test1 = new C2Test();
669 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
670 Assert.AreEqual (ThreadState.Unstarted, TestThread.ThreadState, "#101 Wrong Thread State");
673 //while(!TestThread.IsAlive); //In the MS Documentation this is not necessary
674 //but in the MS SDK it is
675 Assert.IsTrue (TestThread.ThreadState == ThreadState.Running || (TestThread.ThreadState & ThreadState.Unstarted) != 0,
676 "#102 Wrong Thread State: " + TestThread.ThreadState.ToString ());
678 #if MONO_FEATURE_THREAD_ABORT
681 TestThread.Interrupt ();
685 TestUtil.WaitForNotAlive (TestThread, "wait12");
686 // Docs say state will be Stopped, but Aborted happens sometimes (?)
687 Assert.IsTrue ((ThreadState.Stopped & TestThread.ThreadState) != 0 || (ThreadState.Aborted & TestThread.ThreadState) != 0,
688 "#103 Wrong Thread State: " + TestThread.ThreadState.ToString ());
692 [Ignore ("see comment below.")]
693 public void CurrentPrincipal_PrincipalPolicy_NoPrincipal ()
695 // note: switching from PrincipalPolicy won't work inside the same thread
696 // because as soon as a Principal object is created the Policy doesn't matter anymore
697 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.NoPrincipal));
702 #if MONO_FEATURE_THREAD_ABORT
711 [Ignore ("see comment below.")]
712 public void CurrentPrincipal_PrincipalPolicy_UnauthenticatedPrincipal ()
714 // note: switching from PrincipalPolicy won't work inside the same thread
715 // because as soon as a Principal object is created the Policy doesn't matter anymore
716 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.UnauthenticatedPrincipal));
721 #if MONO_FEATURE_THREAD_ABORT
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));
739 #if MONO_FEATURE_THREAD_ABORT
748 public void IPrincipal_CopyOnNewThread ()
750 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("bad"), null);
751 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.CopyOnNewThread));
753 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("good"), null);
757 #if MONO_FEATURE_THREAD_ABORT
767 #if MONO_FEATURE_THREAD_SUSPEND_RESUME
769 public void TestSuspend ()
771 Thread t = new Thread (new ThreadStart (DoCount));
772 t.IsBackground = true;
775 CheckIsRunning ("t1", t);
778 WaitSuspended ("t2", t);
780 CheckIsNotRunning ("t3", t);
783 WaitResumed ("t4", t);
785 CheckIsRunning ("t5", t);
788 TestUtil.WaitForNotAlive (t, "wait13");
789 CheckIsNotRunning ("t6", t);
793 #if MONO_FEATURE_THREAD_SUSPEND_RESUME && MONO_FEATURE_THREAD_ABORT
795 [Category("NotDotNet")] // On MS, ThreadStateException is thrown on Abort: "Thread is suspended; attempting to abort"
796 public void TestSuspendAbort ()
798 Thread t = new Thread (new ThreadStart (DoCount));
799 t.IsBackground = true;
802 CheckIsRunning ("t1", t);
805 WaitSuspended ("t2", t);
807 CheckIsNotRunning ("t3", t);
812 while (t.IsAlive && n < 200) {
817 Assert.IsTrue (n < 200, "Timeout while waiting for abort");
819 CheckIsNotRunning ("t6", t);
824 public void Test_Interrupt ()
826 ManualResetEvent mre = new ManualResetEvent (false);
827 bool interruptedExceptionThrown = false;
829 ThreadPool.QueueUserWorkItem (Test_Interrupt_Worker, Thread.CurrentThread);
837 } catch (ThreadInterruptedException) {
838 Assert.Fail ("ThreadInterruptedException thrown twice");
841 } catch (ThreadInterruptedException) {
842 interruptedExceptionThrown = true;
845 Assert.IsTrue (interruptedExceptionThrown, "ThreadInterruptedException expected.");
849 [ExpectedException (typeof (ArgumentNullException))]
850 public void TestQueueUserWorkItemNullCallback ()
852 ThreadPool.QueueUserWorkItem (null, null);
855 private void Test_Interrupt_Worker (object o)
857 Thread t = o as Thread;
863 public void Test_InterruptCurrentThread ()
865 ManualResetEvent mre = new ManualResetEvent (false);
866 bool interruptedExceptionThrown = false;
868 Thread.CurrentThread.Interrupt ();
872 } catch (ThreadInterruptedException) {
877 public void GetNamedDataSlotTest ()
879 Assert.IsNotNull (Thread.GetNamedDataSlot ("te#st"), "#1");
880 Assert.AreSame (Thread.GetNamedDataSlot ("te#st"), Thread.GetNamedDataSlot ("te#st"), "#2");
883 class DomainClass : MarshalByRefObject {
888 m_thread = new Thread(ThreadProc);
889 m_thread.Start(Thread.CurrentThread);
894 public void ThreadProc (object arg) {
895 success = m_thread == Thread.CurrentThread;
899 #if MONO_FEATURE_MULTIPLE_APPDOMAINS
901 [Category ("NotDotNet")]
902 public void CurrentThread_Domains ()
904 AppDomain ad = AppDomain.CreateDomain ("foo");
905 ad.Load (typeof (DomainClass).Assembly.GetName ());
906 var o = (DomainClass)ad.CreateInstanceAndUnwrap (typeof (DomainClass).Assembly.FullName, typeof (DomainClass).FullName);
907 Assert.IsTrue (o.Run ());
908 AppDomain.Unload (ad);
910 #endif // MONO_FEATURE_MULTIPLE_APPDOMAINS
913 public void SetNameInThreadPoolThread ()
915 Task t = Task.Run (delegate () {
916 Thread.CurrentThread.Name = "ThreadName1";
917 Assert.AreEqual (Thread.CurrentThread.Name, "ThreadName1", "#1");
920 Thread.CurrentThread.Name = "ThreadName2";
922 } catch (InvalidOperationException) {
929 void CheckIsRunning (string s, Thread t)
933 Assert.IsTrue (counter > c, s);
936 void CheckIsNotRunning (string s, Thread t)
940 Assert.AreEqual (counter, c, s);
943 void WaitSuspended (string s, Thread t)
946 ThreadState state = t.ThreadState;
947 while ((state & ThreadState.Suspended) == 0) {
948 Assert.IsTrue ((state & ThreadState.SuspendRequested) != 0, s + ": expected SuspendRequested state");
951 Assert.IsTrue (n < 100, s + ": failed to suspend");
952 state = t.ThreadState;
954 Assert.IsTrue ((state & ThreadState.SuspendRequested) == 0, s + ": SuspendRequested state not expected");
957 void WaitResumed (string s, Thread t)
960 while ((t.ThreadState & ThreadState.Suspended) != 0) {
963 Assert.IsTrue (n < 100, s + ": failed to resume");
967 public void DoCount ()
977 public class ThreadStateTest {
983 public void IsBackGround ()
985 Thread t1 = new Thread (new ThreadStart (Start));
986 Assert.AreEqual (ThreadState.Unstarted, t1.ThreadState, "#A1");
987 Assert.IsFalse (t1.IsBackground, "#A2");
990 Assert.AreEqual (ThreadState.Stopped, t1.ThreadState, "#A3");
993 bool isBackGround = t1.IsBackground;
994 Assert.Fail ("#A4: " + isBackGround.ToString ());
995 } catch (ThreadStateException ex) {
996 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A5");
997 Assert.IsNull (ex.InnerException, "#A6");
998 Assert.IsNotNull (ex.Message, "#A7");
1001 Thread t2 = new Thread (new ThreadStart (Start));
1002 Assert.AreEqual (ThreadState.Unstarted, t2.ThreadState, "#B1");
1003 t2.IsBackground = true;
1004 Assert.AreEqual (ThreadState.Unstarted | ThreadState.Background, t2.ThreadState, "#B2");
1005 Assert.IsTrue (t2.IsBackground, "#B3");
1008 Assert.AreEqual (ThreadState.Stopped, t2.ThreadState, "#B4");
1011 bool isBackGround = t2.IsBackground;
1012 Assert.Fail ("#B5: " + isBackGround.ToString ());
1013 } catch (ThreadStateException ex) {
1014 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B6");
1015 Assert.IsNull (ex.InnerException, "#B7");
1016 Assert.IsNotNull (ex.Message, "#B8");
1023 public class ThreadTest_ManagedThreadId
1027 MBRO mbro = new MBRO ();
1029 class MBRO : MarshalByRefObject {
1033 public string ad_a1;
1034 public string ad_b1;
1035 public string ad_b2;
1036 public string message;
1040 public void ManagedThreadId_AppDomains ()
1042 AppDomain currentDomain = AppDomain.CurrentDomain;
1043 ad1 = AppDomain.CreateDomain ("AppDomain 1", currentDomain.Evidence, currentDomain.SetupInformation);
1044 ad2 = AppDomain.CreateDomain ("AppDomain 2", currentDomain.Evidence, currentDomain.SetupInformation);
1046 Thread a = new Thread (ThreadA);
1047 Thread b = new Thread (ThreadB);
1048 // execute on AppDomain 1 thread A
1049 // execute on AppDomain 2 thread B
1050 // execute on AppDomain 1 thread B - must have same ManagedThreadId as Ad 2 on thread B
1056 AppDomain.Unload (ad1);
1057 AppDomain.Unload (ad2);
1059 if (mbro.message != null)
1060 Assert.Fail (mbro.message);
1062 // 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);
1064 Assert.AreEqual ("AppDomain 1", mbro.ad_a1, "Name #1");
1065 Assert.AreEqual ("AppDomain 1", mbro.ad_b1, "Name #2");
1066 Assert.AreEqual ("AppDomain 2", mbro.ad_b2, "Name #3");
1068 Assert.AreNotEqual (mbro.id_a1, mbro.id_b1, "Id #1");
1069 Assert.AreNotEqual (mbro.id_a1, mbro.id_b2, "Id #2");
1070 Assert.AreEqual (mbro.id_b1, mbro.id_b2, "Id #3");
1072 Assert.AreNotEqual (mbro.id_a1, Thread.CurrentThread.ManagedThreadId, "Id #4");
1073 Assert.AreNotEqual (mbro.id_b1, Thread.CurrentThread.ManagedThreadId, "Id #5");
1074 Assert.AreNotEqual (mbro.id_b2, Thread.CurrentThread.ManagedThreadId, "Id #6");
1075 Assert.AreNotEqual (mbro.ad_a1, AppDomain.CurrentDomain.FriendlyName, "Name #4");
1076 Assert.AreNotEqual (mbro.ad_b1, AppDomain.CurrentDomain.FriendlyName, "Name #5");
1077 Assert.AreNotEqual (mbro.ad_b2, AppDomain.CurrentDomain.FriendlyName, "Name #6");
1082 mbro.id_a1 = Thread.CurrentThread.ManagedThreadId;
1083 mbro.ad_a1 = AppDomain.CurrentDomain.FriendlyName;
1088 mbro.id_b2 = Thread.CurrentThread.ManagedThreadId;
1089 mbro.ad_b2 = AppDomain.CurrentDomain.FriendlyName;
1094 mbro.id_b1 = Thread.CurrentThread.ManagedThreadId;
1095 mbro.ad_b1 = AppDomain.CurrentDomain.FriendlyName;
1098 void ThreadA (object obj)
1100 // Console.WriteLine ("ThreadA");
1102 ad1.DoCallBack (A1);
1103 } catch (Exception ex) {
1104 mbro.message = string.Format ("ThreadA exception: {0}", ex);
1106 // Console.WriteLine ("ThreadA Done");
1109 void ThreadB (object obj)
1111 // Console.WriteLine ("ThreadB");
1113 ad2.DoCallBack (B2);
1114 ad1.DoCallBack (B1);
1115 } catch (Exception ex) {
1116 mbro.message = string.Format ("ThreadB exception: {0}", ex);
1118 // Console.WriteLine ("ThreadB Done");
1123 public class ThreadApartmentTest
1129 [Test] // bug #81658
1130 public void ApartmentState_StoppedThread ()
1132 Thread t1 = new Thread (new ThreadStart (Start));
1136 ApartmentState state = t1.ApartmentState;
1137 Assert.Fail ("#A1: " + state.ToString ());
1138 } catch (ThreadStateException ex) {
1139 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A2");
1140 Assert.IsNull (ex.InnerException, "#A3");
1141 Assert.IsNotNull (ex.Message, "#A4");
1144 Thread t2 = new Thread (new ThreadStart (Start));
1145 t2.IsBackground = true;
1149 ApartmentState state = t2.ApartmentState;
1150 Assert.Fail ("#B1: " + state.ToString ());
1151 } catch (ThreadStateException ex) {
1152 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B2");
1153 Assert.IsNull (ex.InnerException, "#B3");
1154 Assert.IsNotNull (ex.Message, "#B4");
1159 public void ApartmentState_BackGround ()
1161 Thread t1 = new Thread (new ThreadStart (Start));
1162 t1.IsBackground = true;
1163 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "#1");
1164 t1.ApartmentState = ApartmentState.STA;
1165 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#2");
1169 public void TestApartmentState ()
1171 Thread t1 = new Thread (new ThreadStart (Start));
1172 Thread t2 = new Thread (new ThreadStart (Start));
1173 Thread t3 = new Thread (new ThreadStart (Start));
1175 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "Thread1 Default");
1176 Assert.AreEqual (ApartmentState.Unknown, t2.ApartmentState, "Thread2 Default");
1177 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Default");
1179 t1.ApartmentState = ApartmentState.STA;
1180 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1181 t1.ApartmentState = ApartmentState.MTA;
1182 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Twice");
1184 t2.ApartmentState = ApartmentState.MTA;
1185 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Once");
1186 t2.ApartmentState = ApartmentState.STA;
1187 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Twice");
1189 bool exception_occured = false;
1191 t3.ApartmentState = ApartmentState.Unknown;
1194 exception_occured = true;
1196 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Set Invalid");
1197 Assert.IsFalse (exception_occured, "Thread3 Set Invalid Exception Occured");
1200 exception_occured = false;
1202 t1.ApartmentState = ApartmentState.STA;
1205 exception_occured = true;
1207 Assert.IsTrue (exception_occured, "Thread1 Started Invalid Exception Occured");
1211 public void TestSetApartmentStateSameState ()
1213 Thread t1 = new Thread (new ThreadStart (Start));
1214 t1.SetApartmentState (ApartmentState.STA);
1215 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1217 t1.SetApartmentState (ApartmentState.STA);
1218 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set twice");
1222 [ExpectedException(typeof(InvalidOperationException))]
1223 public void TestSetApartmentStateDiffState ()
1225 Thread t1 = new Thread (new ThreadStart (Start));
1226 t1.SetApartmentState (ApartmentState.STA);
1227 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1229 t1.SetApartmentState (ApartmentState.MTA);
1233 public void TestTrySetApartmentState ()
1235 Thread t1 = new Thread (new ThreadStart (Start));
1236 t1.SetApartmentState (ApartmentState.STA);
1237 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1239 bool result = t1.TrySetApartmentState (ApartmentState.MTA);
1240 Assert.IsFalse (result, "#2");
1242 result = t1.TrySetApartmentState (ApartmentState.STA);
1243 Assert.IsTrue (result, "#3");
1247 public void TestTrySetApartmentStateRunning ()
1249 Thread t1 = new Thread (new ThreadStart (Start));
1250 t1.SetApartmentState (ApartmentState.STA);
1251 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1256 t1.TrySetApartmentState (ApartmentState.STA);
1258 } catch (ThreadStateException) {
1265 public void Volatile () {
1267 Thread.VolatileWrite (ref v3, double.MaxValue);
1268 Assert.AreEqual (v3, double.MaxValue);
1271 Thread.VolatileWrite (ref v4, float.MaxValue);
1272 Assert.AreEqual (v4, float.MaxValue);
1276 public void Culture ()
1278 Assert.IsNotNull (Thread.CurrentThread.CurrentCulture, "CurrentCulture");
1279 Assert.IsNotNull (Thread.CurrentThread.CurrentUICulture, "CurrentUICulture");
1283 public void ThreadStartSimple ()
1286 Thread t = new Thread (delegate () {
1287 // ensure the NSAutoreleasePool works
1292 Assert.AreEqual (1, i, "ThreadStart");
1296 public void ParametrizedThreadStart ()
1300 Thread t = new Thread (delegate (object obj) {
1301 // ensure the NSAutoreleasePool works
1308 Assert.AreEqual (1, i, "ParametrizedThreadStart");
1309 Assert.AreEqual (this, arg, "obj");
1313 public void SetNameTpThread () {
1314 ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
1317 static void ThreadProc(Object stateInfo) {
1318 Thread.CurrentThread.Name = "My Worker";
1322 public void GetStackTraces () {
1323 var m = typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static);
1325 var res = (Dictionary<Thread,SD.StackTrace>)typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static).Invoke (null, null);
1326 foreach (var t in res.Keys) {
1327 var st = res [t].ToString ();
1333 public class TestUtil
1335 public static void WaitForNotAlive (Thread t, string s)
1337 WhileAlive (t, true, s);
1340 public static void WaitForAlive (Thread t, string s)
1342 WhileAlive (t, false, s);
1345 public static bool WaitForAliveOrStop (Thread t, string s)
1347 return WhileAliveOrStop (t, false, s);
1350 public static void WhileAlive (Thread t, bool alive, string s)
1352 DateTime ti = DateTime.Now;
1353 while (t.IsAlive == alive) {
1354 if ((DateTime.Now - ti).TotalSeconds > 10) {
1355 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1356 else Assert.Fail ("Timeout while waiting for alive state. " + s);
1361 public static bool WhileAliveOrStop (Thread t, bool alive, string s)
1363 DateTime ti = DateTime.Now;
1364 while (t.IsAlive == alive) {
1365 if (t.ThreadState == ThreadState.Stopped)
1368 if ((DateTime.Now - ti).TotalSeconds > 10) {
1369 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1370 else Assert.Fail ("Timeout while waiting for alive state. " + s);