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 for (int i = 0; i < 10; ++i) {
916 Task t = Task.Run (delegate () {
917 Thread.CurrentThread.Name = "x/" + i;
918 Assert.AreEqual (Thread.CurrentThread.Name, "x/" + i, "#1");
921 Thread.CurrentThread.Name = "y/" + i;
923 } catch (InvalidOperationException) {
931 void CheckIsRunning (string s, Thread t)
935 Assert.IsTrue (counter > c, s);
938 void CheckIsNotRunning (string s, Thread t)
942 Assert.AreEqual (counter, c, s);
945 void WaitSuspended (string s, Thread t)
948 ThreadState state = t.ThreadState;
949 while ((state & ThreadState.Suspended) == 0) {
950 Assert.IsTrue ((state & ThreadState.SuspendRequested) != 0, s + ": expected SuspendRequested state");
953 Assert.IsTrue (n < 100, s + ": failed to suspend");
954 state = t.ThreadState;
956 Assert.IsTrue ((state & ThreadState.SuspendRequested) == 0, s + ": SuspendRequested state not expected");
959 void WaitResumed (string s, Thread t)
962 while ((t.ThreadState & ThreadState.Suspended) != 0) {
965 Assert.IsTrue (n < 100, s + ": failed to resume");
969 public void DoCount ()
979 public class ThreadStateTest {
985 public void IsBackGround ()
987 Thread t1 = new Thread (new ThreadStart (Start));
988 Assert.AreEqual (ThreadState.Unstarted, t1.ThreadState, "#A1");
989 Assert.IsFalse (t1.IsBackground, "#A2");
992 Assert.AreEqual (ThreadState.Stopped, t1.ThreadState, "#A3");
995 bool isBackGround = t1.IsBackground;
996 Assert.Fail ("#A4: " + isBackGround.ToString ());
997 } catch (ThreadStateException ex) {
998 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A5");
999 Assert.IsNull (ex.InnerException, "#A6");
1000 Assert.IsNotNull (ex.Message, "#A7");
1003 Thread t2 = new Thread (new ThreadStart (Start));
1004 Assert.AreEqual (ThreadState.Unstarted, t2.ThreadState, "#B1");
1005 t2.IsBackground = true;
1006 Assert.AreEqual (ThreadState.Unstarted | ThreadState.Background, t2.ThreadState, "#B2");
1007 Assert.IsTrue (t2.IsBackground, "#B3");
1010 Assert.AreEqual (ThreadState.Stopped, t2.ThreadState, "#B4");
1013 bool isBackGround = t2.IsBackground;
1014 Assert.Fail ("#B5: " + isBackGround.ToString ());
1015 } catch (ThreadStateException ex) {
1016 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B6");
1017 Assert.IsNull (ex.InnerException, "#B7");
1018 Assert.IsNotNull (ex.Message, "#B8");
1025 public class ThreadTest_ManagedThreadId
1029 MBRO mbro = new MBRO ();
1031 class MBRO : MarshalByRefObject {
1035 public string ad_a1;
1036 public string ad_b1;
1037 public string ad_b2;
1038 public string message;
1042 public void ManagedThreadId_AppDomains ()
1044 AppDomain currentDomain = AppDomain.CurrentDomain;
1045 ad1 = AppDomain.CreateDomain ("AppDomain 1", currentDomain.Evidence, currentDomain.SetupInformation);
1046 ad2 = AppDomain.CreateDomain ("AppDomain 2", currentDomain.Evidence, currentDomain.SetupInformation);
1048 Thread a = new Thread (ThreadA);
1049 Thread b = new Thread (ThreadB);
1050 // execute on AppDomain 1 thread A
1051 // execute on AppDomain 2 thread B
1052 // execute on AppDomain 1 thread B - must have same ManagedThreadId as Ad 2 on thread B
1058 AppDomain.Unload (ad1);
1059 AppDomain.Unload (ad2);
1061 if (mbro.message != null)
1062 Assert.Fail (mbro.message);
1064 // 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);
1066 Assert.AreEqual ("AppDomain 1", mbro.ad_a1, "Name #1");
1067 Assert.AreEqual ("AppDomain 1", mbro.ad_b1, "Name #2");
1068 Assert.AreEqual ("AppDomain 2", mbro.ad_b2, "Name #3");
1070 Assert.AreNotEqual (mbro.id_a1, mbro.id_b1, "Id #1");
1071 Assert.AreNotEqual (mbro.id_a1, mbro.id_b2, "Id #2");
1072 Assert.AreEqual (mbro.id_b1, mbro.id_b2, "Id #3");
1074 Assert.AreNotEqual (mbro.id_a1, Thread.CurrentThread.ManagedThreadId, "Id #4");
1075 Assert.AreNotEqual (mbro.id_b1, Thread.CurrentThread.ManagedThreadId, "Id #5");
1076 Assert.AreNotEqual (mbro.id_b2, Thread.CurrentThread.ManagedThreadId, "Id #6");
1077 Assert.AreNotEqual (mbro.ad_a1, AppDomain.CurrentDomain.FriendlyName, "Name #4");
1078 Assert.AreNotEqual (mbro.ad_b1, AppDomain.CurrentDomain.FriendlyName, "Name #5");
1079 Assert.AreNotEqual (mbro.ad_b2, AppDomain.CurrentDomain.FriendlyName, "Name #6");
1084 mbro.id_a1 = Thread.CurrentThread.ManagedThreadId;
1085 mbro.ad_a1 = AppDomain.CurrentDomain.FriendlyName;
1090 mbro.id_b2 = Thread.CurrentThread.ManagedThreadId;
1091 mbro.ad_b2 = AppDomain.CurrentDomain.FriendlyName;
1096 mbro.id_b1 = Thread.CurrentThread.ManagedThreadId;
1097 mbro.ad_b1 = AppDomain.CurrentDomain.FriendlyName;
1100 void ThreadA (object obj)
1102 // Console.WriteLine ("ThreadA");
1104 ad1.DoCallBack (A1);
1105 } catch (Exception ex) {
1106 mbro.message = string.Format ("ThreadA exception: {0}", ex);
1108 // Console.WriteLine ("ThreadA Done");
1111 void ThreadB (object obj)
1113 // Console.WriteLine ("ThreadB");
1115 ad2.DoCallBack (B2);
1116 ad1.DoCallBack (B1);
1117 } catch (Exception ex) {
1118 mbro.message = string.Format ("ThreadB exception: {0}", ex);
1120 // Console.WriteLine ("ThreadB Done");
1125 public class ThreadApartmentTest
1131 [Test] // bug #81658
1132 public void ApartmentState_StoppedThread ()
1134 Thread t1 = new Thread (new ThreadStart (Start));
1138 ApartmentState state = t1.ApartmentState;
1139 Assert.Fail ("#A1: " + state.ToString ());
1140 } catch (ThreadStateException ex) {
1141 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A2");
1142 Assert.IsNull (ex.InnerException, "#A3");
1143 Assert.IsNotNull (ex.Message, "#A4");
1146 Thread t2 = new Thread (new ThreadStart (Start));
1147 t2.IsBackground = true;
1151 ApartmentState state = t2.ApartmentState;
1152 Assert.Fail ("#B1: " + state.ToString ());
1153 } catch (ThreadStateException ex) {
1154 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B2");
1155 Assert.IsNull (ex.InnerException, "#B3");
1156 Assert.IsNotNull (ex.Message, "#B4");
1161 public void ApartmentState_BackGround ()
1163 Thread t1 = new Thread (new ThreadStart (Start));
1164 t1.IsBackground = true;
1165 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "#1");
1166 t1.ApartmentState = ApartmentState.STA;
1167 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#2");
1171 public void TestApartmentState ()
1173 Thread t1 = new Thread (new ThreadStart (Start));
1174 Thread t2 = new Thread (new ThreadStart (Start));
1175 Thread t3 = new Thread (new ThreadStart (Start));
1177 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "Thread1 Default");
1178 Assert.AreEqual (ApartmentState.Unknown, t2.ApartmentState, "Thread2 Default");
1179 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Default");
1181 t1.ApartmentState = ApartmentState.STA;
1182 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1183 t1.ApartmentState = ApartmentState.MTA;
1184 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Twice");
1186 t2.ApartmentState = ApartmentState.MTA;
1187 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Once");
1188 t2.ApartmentState = ApartmentState.STA;
1189 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Twice");
1191 bool exception_occured = false;
1193 t3.ApartmentState = ApartmentState.Unknown;
1196 exception_occured = true;
1198 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Set Invalid");
1199 Assert.IsFalse (exception_occured, "Thread3 Set Invalid Exception Occured");
1202 exception_occured = false;
1204 t1.ApartmentState = ApartmentState.STA;
1207 exception_occured = true;
1209 Assert.IsTrue (exception_occured, "Thread1 Started Invalid Exception Occured");
1213 public void TestSetApartmentStateSameState ()
1215 Thread t1 = new Thread (new ThreadStart (Start));
1216 t1.SetApartmentState (ApartmentState.STA);
1217 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1219 t1.SetApartmentState (ApartmentState.STA);
1220 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set twice");
1224 [ExpectedException(typeof(InvalidOperationException))]
1225 public void TestSetApartmentStateDiffState ()
1227 Thread t1 = new Thread (new ThreadStart (Start));
1228 t1.SetApartmentState (ApartmentState.STA);
1229 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1231 t1.SetApartmentState (ApartmentState.MTA);
1235 public void TestTrySetApartmentState ()
1237 Thread t1 = new Thread (new ThreadStart (Start));
1238 t1.SetApartmentState (ApartmentState.STA);
1239 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1241 bool result = t1.TrySetApartmentState (ApartmentState.MTA);
1242 Assert.IsFalse (result, "#2");
1244 result = t1.TrySetApartmentState (ApartmentState.STA);
1245 Assert.IsTrue (result, "#3");
1249 public void TestTrySetApartmentStateRunning ()
1251 Thread t1 = new Thread (new ThreadStart (Start));
1252 t1.SetApartmentState (ApartmentState.STA);
1253 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1258 t1.TrySetApartmentState (ApartmentState.STA);
1260 } catch (ThreadStateException) {
1267 public void Volatile () {
1269 Thread.VolatileWrite (ref v3, double.MaxValue);
1270 Assert.AreEqual (v3, double.MaxValue);
1273 Thread.VolatileWrite (ref v4, float.MaxValue);
1274 Assert.AreEqual (v4, float.MaxValue);
1278 public void Culture ()
1280 Assert.IsNotNull (Thread.CurrentThread.CurrentCulture, "CurrentCulture");
1281 Assert.IsNotNull (Thread.CurrentThread.CurrentUICulture, "CurrentUICulture");
1285 public void ThreadStartSimple ()
1288 Thread t = new Thread (delegate () {
1289 // ensure the NSAutoreleasePool works
1294 Assert.AreEqual (1, i, "ThreadStart");
1298 public void ParametrizedThreadStart ()
1302 Thread t = new Thread (delegate (object obj) {
1303 // ensure the NSAutoreleasePool works
1310 Assert.AreEqual (1, i, "ParametrizedThreadStart");
1311 Assert.AreEqual (this, arg, "obj");
1315 public void SetNameTpThread () {
1316 ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
1319 static void ThreadProc(Object stateInfo) {
1320 Thread.CurrentThread.Name = "My Worker";
1324 public void GetStackTraces () {
1325 var m = typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static);
1327 var res = (Dictionary<Thread,SD.StackTrace>)typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static).Invoke (null, null);
1328 foreach (var t in res.Keys) {
1329 var st = res [t].ToString ();
1335 public class TestUtil
1337 public static void WaitForNotAlive (Thread t, string s)
1339 WhileAlive (t, true, s);
1342 public static void WaitForAlive (Thread t, string s)
1344 WhileAlive (t, false, s);
1347 public static bool WaitForAliveOrStop (Thread t, string s)
1349 return WhileAliveOrStop (t, false, s);
1352 public static void WhileAlive (Thread t, bool alive, string s)
1354 DateTime ti = DateTime.Now;
1355 while (t.IsAlive == alive) {
1356 if ((DateTime.Now - ti).TotalSeconds > 10) {
1357 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1358 else Assert.Fail ("Timeout while waiting for alive state. " + s);
1363 public static bool WhileAliveOrStop (Thread t, bool alive, string s)
1365 DateTime ti = DateTime.Now;
1366 while (t.IsAlive == alive) {
1367 if (t.ThreadState == ThreadState.Stopped)
1370 if ((DateTime.Now - ti).TotalSeconds > 10) {
1371 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1372 else Assert.Fail ("Timeout while waiting for alive state. " + s);