1 // ThreadTest.cs - NUnit Test Cases for the System.Threading.Thread class
4 // Eduardo Garcia Cebollero (kiwnix@yahoo.es)
5 // Sebastien Pouliot <sebastien@ximian.com>
7 // (C) Eduardo Garcia Cebollero.
8 // (C) Ximian, Inc. http://www.ximian.com
9 // (C) 2004 Novell (http://www.novell.com)
13 using System.Globalization;
14 using System.Security.Principal;
15 using System.Threading;
16 using System.Reflection;
17 using System.Collections.Generic;
18 using SD = System.Diagnostics;
20 using NUnit.Framework;
22 namespace MonoTests.System.Threading
24 // These tests seem to hang the 2.0 framework. So they are disabled for now
25 // Don't reenable them until you can run a few thousand times on an SMP box.
26 [Category ("NotWorking")]
27 public class ThreadedPrincipalTest
29 public static void NoPrincipal ()
31 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.NoPrincipal);
32 IPrincipal p = Thread.CurrentPrincipal;
33 Assert.IsNull (p, "#1");
35 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
36 Assert.IsNotNull (Thread.CurrentPrincipal, "#2");
38 Thread.CurrentPrincipal = null;
39 Assert.IsNull (Thread.CurrentPrincipal, "#3");
40 // in this case we can return to null
43 public static void UnauthenticatedPrincipal ()
45 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.UnauthenticatedPrincipal);
46 IPrincipal p = Thread.CurrentPrincipal;
47 Assert.IsNotNull (p, "#1");
48 Assert.IsTrue ((p is GenericPrincipal), "#2");
49 Assert.AreEqual (String.Empty, p.Identity.Name, "#3");
50 Assert.AreEqual (String.Empty, p.Identity.AuthenticationType, "#4");
51 Assert.IsFalse (p.Identity.IsAuthenticated, "#5");
53 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
54 Assert.IsNotNull (Thread.CurrentPrincipal, "#6");
56 Thread.CurrentPrincipal = null;
57 Assert.IsNotNull (Thread.CurrentPrincipal, "#7");
58 // in this case we can't return to null
61 public static void WindowsPrincipal ()
63 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.WindowsPrincipal);
64 IPrincipal p = Thread.CurrentPrincipal;
65 Assert.IsNotNull (p, "#1");
66 Assert.IsTrue ((p is WindowsPrincipal), "#2");
67 Assert.IsNotNull (p.Identity.Name, "#3");
68 Assert.IsNotNull (p.Identity.AuthenticationType, "#4");
69 Assert.IsTrue (p.Identity.IsAuthenticated, "#5");
71 // note: we can switch from a WindowsPrincipal to a GenericPrincipal
72 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
73 Assert.IsNotNull (Thread.CurrentPrincipal, "#6");
75 Thread.CurrentPrincipal = null;
76 Assert.IsNotNull (Thread.CurrentPrincipal, "#7");
77 // in this case we can't return to null
80 public static void CopyOnNewThread ()
82 Assert.IsNotNull (Thread.CurrentPrincipal, "#1");
83 Assert.AreEqual ("good", Thread.CurrentPrincipal.Identity.Name, "#2");
88 [Category("MobileNotWorking")] // Abort #10240
89 public class ThreadTest
91 //TimeSpan Infinite = new TimeSpan (-10000); // -10000 ticks == -1 ms
92 TimeSpan SmallNegative = new TimeSpan (-2); // between 0 and -1.0 (infinite) ms
93 TimeSpan Negative = new TimeSpan (-20000); // really negative
94 //TimeSpan MaxValue = TimeSpan.FromMilliseconds ((long) Int32.MaxValue);
95 TimeSpan TooLarge = TimeSpan.FromMilliseconds ((long) Int32.MaxValue + 1);
102 switch (Environment.OSVersion.Platform) {
103 case PlatformID.Win32NT:
104 case PlatformID.Win32S:
105 case PlatformID.Win32Windows:
106 case PlatformID.WinCE:
111 // check a class in mscorlib to determine if we're running on Mono
112 if (Type.GetType ("Mono.Runtime", false) != null)
116 //Some Classes to test as threads
120 public Thread thread1;
126 thread1 = (Thread)null;
128 endm1 = endm2 = false;
131 public void TestMethod()
139 public void TestMethod2()
141 if (!(thread1==(Thread)null) )
152 public bool run = false;
159 public void TestMethod()
174 public C1Test sub_class;
175 public Thread sub_thread;
179 sub_class = new C1Test();
180 sub_thread = new Thread(new ThreadStart(sub_class.TestMethod));
183 public void TestMethod1()
187 #if MONO_FEATURE_THREAD_ABORT
190 sub_thread.Interrupt ();
197 public C1Test class1;
198 public C1Test class2;
199 public Thread thread1;
200 public Thread thread2;
208 class1 = new C1Test();
209 class2 = new C1Test();
210 thread1 = new Thread(new ThreadStart(class1.TestMethod));
211 thread2 = new Thread(new ThreadStart(class2.TestMethod));
214 public void TestMethod1()
217 TestUtil.WaitForAlive (thread1, "wait1");
220 TestUtil.WaitForAlive (thread2, "wait2");
222 #if MONO_FEATURE_THREAD_ABORT
225 thread1.Interrupt ();
227 TestUtil.WaitForNotAlive (thread1, "wait3");
229 #if MONO_FEATURE_THREAD_ABORT
232 thread2.Interrupt ();
234 TestUtil.WaitForNotAlive (thread2, "wait4");
238 public void TestMethod2()
246 public void TestCtor1()
248 C1Test test1 = new C1Test();
249 Thread t = new Thread (new ThreadStart (test1.TestMethod));
251 Assert.IsTrue (t.CurrentCulture.IsReadOnly, "CurrentCulture.IsReadOnly");
252 Assert.IsFalse (t.IsAlive, "IsAlive");
253 Assert.IsFalse (t.IsBackground, "IsBackground");
254 Assert.IsNull (t.Name, "Name");
255 Assert.AreEqual (ThreadState.Unstarted, t.ThreadState, "ThreadState");
259 [Category ("NotWorking")] // we're not sharing (read-only) CultureInfo
260 public void CultureInfo_Shared_Across_Threads ()
262 Thread t = new Thread (TestCtor1);
263 Assert.AreSame (t.CurrentCulture, t.CurrentUICulture, "Culture");
265 Assert.AreSame (t.CurrentCulture, CultureInfo.CurrentCulture, "CultureInfo.CurrentCulture");
266 Assert.AreSame (t.CurrentUICulture, CultureInfo.CurrentUICulture, "CultureInfo.CurrentUICulture");
268 Assert.AreSame (t.CurrentCulture, Thread.CurrentThread.CurrentCulture, "Thread.CurrentThread.CurrentCulture");
269 Assert.AreSame (t.CurrentUICulture, Thread.CurrentThread.CurrentUICulture, "Thread.CurrentThread.CurrentUICulture");
272 [Test] // bug #325566
273 public void GetHashCodeTest ()
275 C1Test test1 = new C1Test ();
276 Thread tA = new Thread (new ThreadStart (test1.TestMethod));
277 int hA1 = tA.GetHashCode ();
278 Assert.IsTrue (hA1 > 0, "#A1");
280 int hA2 = tA.GetHashCode ();
281 Assert.AreEqual (hA1, hA2, "#A2");
283 int hA3 = tA.GetHashCode ();
284 Assert.AreEqual (hA1, hA3, "#A3");
285 Assert.AreEqual (hA1, tA.ManagedThreadId, "#A4");
287 test1 = new C1Test ();
288 Thread tB = new Thread (new ThreadStart (test1.TestMethod));
289 int hB1 = tB.GetHashCode ();
290 Assert.IsTrue (hB1 > 0, "#B1");
292 int hB2 = tB.GetHashCode ();
293 Assert.AreEqual (hB1, hB2, "#B2");
295 int hB3 = tB.GetHashCode ();
296 Assert.AreEqual (hB1, hB3, "#B3");
297 Assert.AreEqual (hB1, tB.ManagedThreadId, "#B4");
298 Assert.IsFalse (hA2 == hB2, "#B5");
302 public void ManagedThreadId ()
304 C1Test test1 = new C1Test ();
305 Thread t1 = new Thread (new ThreadStart (test1.TestMethod));
306 int mtA1 = t1.ManagedThreadId;
308 int mtA2 = t1.ManagedThreadId;
310 int mtA3 = t1.ManagedThreadId;
311 Assert.AreEqual (mtA1, mtA2, "#A1");
312 Assert.AreEqual (mtA2, mtA3, "#A2");
314 test1 = new C1Test ();
315 Thread t2 = new Thread (new ThreadStart (test1.TestMethod));
316 int mtB1 = t2.ManagedThreadId;
318 int mtB2 = t2.ManagedThreadId;
320 int mtB3 = t2.ManagedThreadId;
321 Assert.AreEqual (mtB1, mtB2, "#B1");
322 Assert.AreEqual (mtB2, mtB3, "#B2");
323 Assert.IsFalse (mtB1 == mtA1, "#B3");
327 [Category ("NotDotNet")] // it hangs.
328 public void TestStart()
330 if (is_win32 && is_mono)
331 Assert.Fail ("This test fails on Win32. The test should be fixed.");
333 C1Test test1 = new C1Test();
334 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
337 Assert.AreEqual (10, test1.cnt, "#1");
340 C2Test test1 = new C2Test();
341 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
343 #if MONO_FEATURE_THREAD_ABORT
346 TestThread.Interrupt ();
351 } catch (ThreadStateException) {
355 C2Test test1 = new C2Test();
356 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
360 bool started = (TestThread.ThreadState == ThreadState.Running);
361 Assert.AreEqual (started, test1.run, "#15 Thread Is not in the correct state: ");
362 #if MONO_FEATURE_THREAD_ABORT
365 TestThread.Interrupt ();
371 public void TestApartmentState ()
373 if (is_win32 && is_mono)
374 Assert.Fail ("This test fails on mono on win32. Our runtime should be fixed.");
376 C2Test test1 = new C2Test();
377 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
378 Assert.AreEqual (ApartmentState.Unknown, TestThread.ApartmentState, "#1");
380 TestUtil.WaitForAlive (TestThread, "wait5");
381 Assert.AreEqual (ApartmentState.MTA, TestThread.ApartmentState, "#2");
382 #if MONO_FEATURE_THREAD_ABORT
385 TestThread.Interrupt ();
390 [Category ("NotWorking")] // setting the priority of a Thread before it is started isn't implemented in Mono yet
391 public void TestPriority1()
393 if (is_win32 && is_mono)
394 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
396 C2Test test1 = new C2Test();
397 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
399 TestThread.Priority=ThreadPriority.BelowNormal;
400 ThreadPriority before = TestThread.Priority;
401 Assert.AreEqual (ThreadPriority.BelowNormal, before, "#40 Unexpected priority before thread start: ");
403 TestUtil.WaitForAlive (TestThread, "wait7");
404 ThreadPriority after = TestThread.Priority;
405 Assert.AreEqual (before, after, "#41 Unexpected Priority Change: ");
407 #if MONO_FEATURE_THREAD_ABORT
410 TestThread.Interrupt ();
415 #if MONO_FEATURE_THREAD_ABORT
417 [Category ("NotDotNet")] // on MS, Thread is still in AbortRequested state when Start is invoked
418 public void AbortUnstarted ()
420 C2Test test1 = new C2Test();
421 Thread th = new Thread (new ThreadStart (test1.TestMethod));
428 [Category ("NotDotNet")] // on MS, ThreadState is immediately Stopped after Abort
429 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
430 public void TestPriority2()
432 C2Test test1 = new C2Test();
433 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
435 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#42 Incorrect Priority in New thread: ");
437 TestUtil.WaitForAliveOrStop (TestThread, "wait8");
438 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#43 Incorrect Priority in Started thread: ");
440 #if MONO_FEATURE_THREAD_ABORT
443 TestThread.Interrupt ();
446 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#44 Incorrect Priority in Aborted thread: ");
450 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
451 public void TestPriority3()
453 C2Test test1 = new C2Test();
454 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
457 TestThread.Priority = ThreadPriority.Lowest;
458 Assert.AreEqual (ThreadPriority.Lowest, TestThread.Priority, "#45A Incorrect Priority:");
459 TestThread.Priority = ThreadPriority.BelowNormal;
460 Assert.AreEqual (ThreadPriority.BelowNormal, TestThread.Priority, "#45B Incorrect Priority:");
461 TestThread.Priority = ThreadPriority.Normal;
462 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#45C Incorrect Priority:");
463 TestThread.Priority = ThreadPriority.AboveNormal;
464 Assert.AreEqual (ThreadPriority.AboveNormal, TestThread.Priority, "#45D Incorrect Priority:");
465 TestThread.Priority = ThreadPriority.Highest;
466 Assert.AreEqual (ThreadPriority.Highest, TestThread.Priority, "#45E Incorrect Priority:");
469 #if MONO_FEATURE_THREAD_ABORT
472 TestThread.Interrupt ();
478 public void TestUndivisibleByPageSizeMaxStackSize ()
480 const int undivisible_stacksize = 1048573;
482 var thread = new Thread (new ThreadStart (delegate {}), undivisible_stacksize);
488 public void TestIsBackground1 ()
490 if (is_win32 && is_mono)
491 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
493 C2Test test1 = new C2Test();
494 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
497 TestUtil.WaitForAlive (TestThread, "wait9");
498 bool state = TestThread.IsBackground;
499 Assert.IsFalse (state, "#51 IsBackground not set at the default state: ");
501 #if MONO_FEATURE_THREAD_ABORT
504 TestThread.Interrupt ();
510 public void TestIsBackground2 ()
512 C2Test test1 = new C2Test();
513 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
514 TestThread.IsBackground = true;
518 #if MONO_FEATURE_THREAD_ABORT
521 TestThread.Interrupt ();
525 if (TestThread.IsAlive) {
527 Assert.IsTrue (TestThread.IsBackground, "#52 Is Background Changed to Start ");
528 } catch (ThreadStateException) {
529 // Ignore if thread died meantime
535 public void TestName()
537 if (is_win32 && is_mono)
538 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
540 C2Test test1 = new C2Test();
541 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
544 TestUtil.WaitForAlive (TestThread, "wait10");
545 string name = TestThread.Name;
546 Assert.IsNull (name, "#61 Name set when mustn't be set: ");
547 string newname = "Testing....";
548 TestThread.Name = newname;
549 Assert.AreEqual (newname, TestThread.Name, "#62 Name not set when must be set: ");
551 #if MONO_FEATURE_THREAD_ABORT
554 TestThread.Interrupt ();
562 Thread t = new Thread (new ThreadStart (Name));
563 Assert.IsNull (t.Name, "Name-1");
565 Assert.IsNull (t.Name, "Name-2");
569 [ExpectedException (typeof (InvalidOperationException))]
570 public void Rename ()
572 Thread t = new Thread (new ThreadStart (Rename));
578 public void TestNestedThreads1()
580 C3Test test1 = new C3Test();
581 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
584 TestUtil.WaitForAlive (TestThread, "wait11");
586 #if MONO_FEATURE_THREAD_ABORT
589 TestThread.Interrupt ();
595 public void TestNestedThreads2()
597 C4Test test1 = new C4Test();
598 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
602 #if MONO_FEATURE_THREAD_ABORT
605 TestThread.Interrupt ();
611 public void TestJoin1()
613 C1Test test1 = new C1Test();
614 C1Test test2 = new C1Test();
615 Thread thread1 = new Thread(new ThreadStart(test1.TestMethod));
616 Thread thread2 = new Thread(new ThreadStart(test1.TestMethod2));
622 #if MONO_FEATURE_THREAD_ABORT
626 thread1.Interrupt ();
627 thread2.Interrupt ();
633 [ExpectedException (typeof (ArgumentOutOfRangeException))]
634 public void Join_Int32_Negative ()
636 // -1 is Timeout.Infinite
637 Thread.CurrentThread.Join (-2);
641 [ExpectedException (typeof (ArgumentOutOfRangeException))]
642 public void Join_TimeSpan_Negative ()
644 Thread.CurrentThread.Join (Negative);
648 [ExpectedException (typeof (ArgumentOutOfRangeException))]
649 public void Join_TimeSpan_TooLarge ()
651 Thread.CurrentThread.Join (TooLarge);
655 public void Join_TimeSpan_SmallNegative ()
657 Thread.CurrentThread.Join (SmallNegative);
661 [ExpectedException (typeof (ArgumentOutOfRangeException))]
662 public void Sleep_Int32_Negative ()
664 // -1 is Timeout.Infinite
669 public void Sleep_TimeSpan_SmallNegative ()
671 Thread.Sleep (SmallNegative);
675 [ExpectedException (typeof (ArgumentOutOfRangeException))]
676 public void Sleep_TimeSpan_Negative ()
678 Thread.Sleep (Negative);
682 [ExpectedException (typeof (ArgumentOutOfRangeException))]
683 public void Sleep_TimeSpan_TooLarge ()
685 Thread.Sleep (TooLarge);
689 public void SpinWait ()
691 // no exception for negative numbers
692 Thread.SpinWait (Int32.MinValue);
697 public void TestThreadState ()
699 if (is_win32 && is_mono)
700 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
702 //TODO: Test The rest of the possible transitions
703 C2Test test1 = new C2Test();
704 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
705 Assert.AreEqual (ThreadState.Unstarted, TestThread.ThreadState, "#101 Wrong Thread State");
708 //while(!TestThread.IsAlive); //In the MS Documentation this is not necessary
709 //but in the MS SDK it is
710 Assert.IsTrue (TestThread.ThreadState == ThreadState.Running || (TestThread.ThreadState & ThreadState.Unstarted) != 0,
711 "#102 Wrong Thread State: " + TestThread.ThreadState.ToString ());
713 #if MONO_FEATURE_THREAD_ABORT
716 TestThread.Interrupt ();
720 TestUtil.WaitForNotAlive (TestThread, "wait12");
721 // Docs say state will be Stopped, but Aborted happens sometimes (?)
722 Assert.IsTrue ((ThreadState.Stopped & TestThread.ThreadState) != 0 || (ThreadState.Aborted & TestThread.ThreadState) != 0,
723 "#103 Wrong Thread State: " + TestThread.ThreadState.ToString ());
727 [Ignore ("see comment below.")]
728 public void CurrentPrincipal_PrincipalPolicy_NoPrincipal ()
730 // note: switching from PrincipalPolicy won't work inside the same thread
731 // because as soon as a Principal object is created the Policy doesn't matter anymore
732 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.NoPrincipal));
737 #if MONO_FEATURE_THREAD_ABORT
746 [Ignore ("see comment below.")]
747 public void CurrentPrincipal_PrincipalPolicy_UnauthenticatedPrincipal ()
749 // note: switching from PrincipalPolicy won't work inside the same thread
750 // because as soon as a Principal object is created the Policy doesn't matter anymore
751 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.UnauthenticatedPrincipal));
756 #if MONO_FEATURE_THREAD_ABORT
765 public void CurrentPrincipal_PrincipalPolicy_WindowsPrincipal ()
767 // note: switching from PrincipalPolicy won't work inside the same thread
768 // because as soon as a Principal object is created the Policy doesn't matter anymore
769 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.WindowsPrincipal));
774 #if MONO_FEATURE_THREAD_ABORT
783 public void IPrincipal_CopyOnNewThread ()
785 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("bad"), null);
786 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.CopyOnNewThread));
788 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("good"), null);
792 #if MONO_FEATURE_THREAD_ABORT
802 #if MONO_FEATURE_THREAD_SUSPEND_RESUME
804 public void TestSuspend ()
806 Thread t = new Thread (new ThreadStart (DoCount));
807 t.IsBackground = true;
810 CheckIsRunning ("t1", t);
813 WaitSuspended ("t2", t);
815 CheckIsNotRunning ("t3", t);
818 WaitResumed ("t4", t);
820 CheckIsRunning ("t5", t);
823 TestUtil.WaitForNotAlive (t, "wait13");
824 CheckIsNotRunning ("t6", t);
828 #if MONO_FEATURE_THREAD_SUSPEND_RESUME && MONO_FEATURE_THREAD_ABORT
830 [Category("NotDotNet")] // On MS, ThreadStateException is thrown on Abort: "Thread is suspended; attempting to abort"
831 public void TestSuspendAbort ()
833 if (is_win32 && is_mono)
834 Assert.Fail ("This test fails on Win32. The test should be fixed.");
836 Thread t = new Thread (new ThreadStart (DoCount));
837 t.IsBackground = true;
840 CheckIsRunning ("t1", t);
843 WaitSuspended ("t2", t);
845 CheckIsNotRunning ("t3", t);
850 while (t.IsAlive && n < 200) {
855 Assert.IsTrue (n < 200, "Timeout while waiting for abort");
857 CheckIsNotRunning ("t6", t);
862 public void Test_Interrupt ()
864 ManualResetEvent mre = new ManualResetEvent (false);
865 bool interruptedExceptionThrown = false;
867 ThreadPool.QueueUserWorkItem (Test_Interrupt_Worker, Thread.CurrentThread);
875 } catch (ThreadInterruptedException) {
876 Assert.Fail ("ThreadInterruptedException thrown twice");
879 } catch (ThreadInterruptedException) {
880 interruptedExceptionThrown = true;
883 Assert.IsTrue (interruptedExceptionThrown, "ThreadInterruptedException expected.");
887 [ExpectedException (typeof (ArgumentNullException))]
888 public void TestQueueUserWorkItemNullCallback ()
890 ThreadPool.QueueUserWorkItem (null, null);
893 private void Test_Interrupt_Worker (object o)
895 Thread t = o as Thread;
901 [Category ("NotDotNet")] // it crashes nunit.
902 public void Test_InterruptCurrentThread ()
904 ManualResetEvent mre = new ManualResetEvent (false);
905 bool interruptedExceptionThrown = false;
907 Thread.CurrentThread.Interrupt ();
911 } catch (ThreadInterruptedException) {
916 public void GetNamedDataSlotTest ()
918 Assert.IsNotNull (Thread.GetNamedDataSlot ("te#st"), "#1");
919 Assert.AreSame (Thread.GetNamedDataSlot ("te#st"), Thread.GetNamedDataSlot ("te#st"), "#2");
922 class DomainClass : MarshalByRefObject {
927 m_thread = new Thread(ThreadProc);
928 m_thread.Start(Thread.CurrentThread);
933 public void ThreadProc (object arg) {
934 success = m_thread == Thread.CurrentThread;
938 #if MONO_FEATURE_MULTIPLE_APPDOMAINS
940 public void CurrentThread_Domains ()
942 AppDomain ad = AppDomain.CreateDomain ("foo");
943 ad.Load (typeof (DomainClass).Assembly.GetName ());
944 var o = (DomainClass)ad.CreateInstanceAndUnwrap (typeof (DomainClass).Assembly.FullName, typeof (DomainClass).FullName);
945 Assert.IsTrue (o.Run ());
946 AppDomain.Unload (ad);
948 #endif // MONO_FEATURE_MULTIPLE_APPDOMAINS
950 void CheckIsRunning (string s, Thread t)
954 Assert.IsTrue (counter > c, s);
957 void CheckIsNotRunning (string s, Thread t)
961 Assert.AreEqual (counter, c, s);
964 void WaitSuspended (string s, Thread t)
967 ThreadState state = t.ThreadState;
968 while ((state & ThreadState.Suspended) == 0) {
969 Assert.IsTrue ((state & ThreadState.SuspendRequested) != 0, s + ": expected SuspendRequested state");
972 Assert.IsTrue (n < 100, s + ": failed to suspend");
973 state = t.ThreadState;
975 Assert.IsTrue ((state & ThreadState.SuspendRequested) == 0, s + ": SuspendRequested state not expected");
978 void WaitResumed (string s, Thread t)
981 while ((t.ThreadState & ThreadState.Suspended) != 0) {
984 Assert.IsTrue (n < 100, s + ": failed to resume");
988 public void DoCount ()
998 public class ThreadStateTest {
1003 [Test] // bug #81720
1004 public void IsBackGround ()
1006 Thread t1 = new Thread (new ThreadStart (Start));
1007 Assert.AreEqual (ThreadState.Unstarted, t1.ThreadState, "#A1");
1008 Assert.IsFalse (t1.IsBackground, "#A2");
1011 Assert.AreEqual (ThreadState.Stopped, t1.ThreadState, "#A3");
1014 bool isBackGround = t1.IsBackground;
1015 Assert.Fail ("#A4: " + isBackGround.ToString ());
1016 } catch (ThreadStateException ex) {
1017 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A5");
1018 Assert.IsNull (ex.InnerException, "#A6");
1019 Assert.IsNotNull (ex.Message, "#A7");
1022 Thread t2 = new Thread (new ThreadStart (Start));
1023 Assert.AreEqual (ThreadState.Unstarted, t2.ThreadState, "#B1");
1024 t2.IsBackground = true;
1025 Assert.AreEqual (ThreadState.Unstarted | ThreadState.Background, t2.ThreadState, "#B2");
1026 Assert.IsTrue (t2.IsBackground, "#B3");
1029 Assert.AreEqual (ThreadState.Stopped, t2.ThreadState, "#B4");
1032 bool isBackGround = t2.IsBackground;
1033 Assert.Fail ("#B5: " + isBackGround.ToString ());
1034 } catch (ThreadStateException ex) {
1035 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B6");
1036 Assert.IsNull (ex.InnerException, "#B7");
1037 Assert.IsNotNull (ex.Message, "#B8");
1044 public class ThreadTest_ManagedThreadId
1048 MBRO mbro = new MBRO ();
1050 class MBRO : MarshalByRefObject {
1054 public string ad_a1;
1055 public string ad_b1;
1056 public string ad_b2;
1057 public string message;
1061 public void ManagedThreadId_AppDomains ()
1063 AppDomain currentDomain = AppDomain.CurrentDomain;
1064 ad1 = AppDomain.CreateDomain ("AppDomain 1", currentDomain.Evidence, currentDomain.SetupInformation);
1065 ad2 = AppDomain.CreateDomain ("AppDomain 2", currentDomain.Evidence, currentDomain.SetupInformation);
1067 Thread a = new Thread (ThreadA);
1068 Thread b = new Thread (ThreadB);
1069 // execute on AppDomain 1 thread A
1070 // execute on AppDomain 2 thread B
1071 // execute on AppDomain 1 thread B - must have same ManagedThreadId as Ad 2 on thread B
1077 AppDomain.Unload (ad1);
1078 AppDomain.Unload (ad2);
1080 if (mbro.message != null)
1081 Assert.Fail (mbro.message);
1083 // 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);
1085 Assert.AreEqual ("AppDomain 1", mbro.ad_a1, "Name #1");
1086 Assert.AreEqual ("AppDomain 1", mbro.ad_b1, "Name #2");
1087 Assert.AreEqual ("AppDomain 2", mbro.ad_b2, "Name #3");
1089 Assert.AreNotEqual (mbro.id_a1, mbro.id_b1, "Id #1");
1090 Assert.AreNotEqual (mbro.id_a1, mbro.id_b2, "Id #2");
1091 Assert.AreEqual (mbro.id_b1, mbro.id_b2, "Id #3");
1093 Assert.AreNotEqual (mbro.id_a1, Thread.CurrentThread.ManagedThreadId, "Id #4");
1094 Assert.AreNotEqual (mbro.id_b1, Thread.CurrentThread.ManagedThreadId, "Id #5");
1095 Assert.AreNotEqual (mbro.id_b2, Thread.CurrentThread.ManagedThreadId, "Id #6");
1096 Assert.AreNotEqual (mbro.ad_a1, AppDomain.CurrentDomain.FriendlyName, "Name #4");
1097 Assert.AreNotEqual (mbro.ad_b1, AppDomain.CurrentDomain.FriendlyName, "Name #5");
1098 Assert.AreNotEqual (mbro.ad_b2, AppDomain.CurrentDomain.FriendlyName, "Name #6");
1103 mbro.id_a1 = Thread.CurrentThread.ManagedThreadId;
1104 mbro.ad_a1 = AppDomain.CurrentDomain.FriendlyName;
1109 mbro.id_b2 = Thread.CurrentThread.ManagedThreadId;
1110 mbro.ad_b2 = AppDomain.CurrentDomain.FriendlyName;
1115 mbro.id_b1 = Thread.CurrentThread.ManagedThreadId;
1116 mbro.ad_b1 = AppDomain.CurrentDomain.FriendlyName;
1119 void ThreadA (object obj)
1121 // Console.WriteLine ("ThreadA");
1123 ad1.DoCallBack (A1);
1124 } catch (Exception ex) {
1125 mbro.message = string.Format ("ThreadA exception: {0}", ex);
1127 // Console.WriteLine ("ThreadA Done");
1130 void ThreadB (object obj)
1132 // Console.WriteLine ("ThreadB");
1134 ad2.DoCallBack (B2);
1135 ad1.DoCallBack (B1);
1136 } catch (Exception ex) {
1137 mbro.message = string.Format ("ThreadB exception: {0}", ex);
1139 // Console.WriteLine ("ThreadB Done");
1144 public class ThreadApartmentTest
1150 [Test] // bug #81658
1151 public void ApartmentState_StoppedThread ()
1153 Thread t1 = new Thread (new ThreadStart (Start));
1157 ApartmentState state = t1.ApartmentState;
1158 Assert.Fail ("#A1: " + state.ToString ());
1159 } catch (ThreadStateException ex) {
1160 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A2");
1161 Assert.IsNull (ex.InnerException, "#A3");
1162 Assert.IsNotNull (ex.Message, "#A4");
1165 Thread t2 = new Thread (new ThreadStart (Start));
1166 t2.IsBackground = true;
1170 ApartmentState state = t2.ApartmentState;
1171 Assert.Fail ("#B1: " + state.ToString ());
1172 } catch (ThreadStateException ex) {
1173 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B2");
1174 Assert.IsNull (ex.InnerException, "#B3");
1175 Assert.IsNotNull (ex.Message, "#B4");
1180 public void ApartmentState_BackGround ()
1182 Thread t1 = new Thread (new ThreadStart (Start));
1183 t1.IsBackground = true;
1184 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "#1");
1185 t1.ApartmentState = ApartmentState.STA;
1186 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#2");
1190 public void TestApartmentState ()
1192 Thread t1 = new Thread (new ThreadStart (Start));
1193 Thread t2 = new Thread (new ThreadStart (Start));
1194 Thread t3 = new Thread (new ThreadStart (Start));
1196 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "Thread1 Default");
1197 Assert.AreEqual (ApartmentState.Unknown, t2.ApartmentState, "Thread2 Default");
1198 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Default");
1200 t1.ApartmentState = ApartmentState.STA;
1201 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1202 t1.ApartmentState = ApartmentState.MTA;
1203 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Twice");
1205 t2.ApartmentState = ApartmentState.MTA;
1206 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Once");
1207 t2.ApartmentState = ApartmentState.STA;
1208 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Twice");
1210 bool exception_occured = false;
1212 t3.ApartmentState = ApartmentState.Unknown;
1215 exception_occured = true;
1217 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Set Invalid");
1218 Assert.IsFalse (exception_occured, "Thread3 Set Invalid Exception Occured");
1221 exception_occured = false;
1223 t1.ApartmentState = ApartmentState.STA;
1226 exception_occured = true;
1228 Assert.IsTrue (exception_occured, "Thread1 Started Invalid Exception Occured");
1232 public void TestSetApartmentStateSameState ()
1234 Thread t1 = new Thread (new ThreadStart (Start));
1235 t1.SetApartmentState (ApartmentState.STA);
1236 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1238 t1.SetApartmentState (ApartmentState.STA);
1239 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set twice");
1243 [ExpectedException(typeof(InvalidOperationException))]
1244 public void TestSetApartmentStateDiffState ()
1246 Thread t1 = new Thread (new ThreadStart (Start));
1247 t1.SetApartmentState (ApartmentState.STA);
1248 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1250 t1.SetApartmentState (ApartmentState.MTA);
1254 public void TestTrySetApartmentState ()
1256 Thread t1 = new Thread (new ThreadStart (Start));
1257 t1.SetApartmentState (ApartmentState.STA);
1258 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1260 bool result = t1.TrySetApartmentState (ApartmentState.MTA);
1261 Assert.IsFalse (result, "#2");
1263 result = t1.TrySetApartmentState (ApartmentState.STA);
1264 Assert.IsTrue (result, "#3");
1268 public void TestTrySetApartmentStateRunning ()
1270 Thread t1 = new Thread (new ThreadStart (Start));
1271 t1.SetApartmentState (ApartmentState.STA);
1272 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1277 t1.TrySetApartmentState (ApartmentState.STA);
1279 } catch (ThreadStateException) {
1286 public void Volatile () {
1288 Thread.VolatileWrite (ref v3, double.MaxValue);
1289 Assert.AreEqual (v3, double.MaxValue);
1292 Thread.VolatileWrite (ref v4, float.MaxValue);
1293 Assert.AreEqual (v4, float.MaxValue);
1297 public void Culture ()
1299 Assert.IsNotNull (Thread.CurrentThread.CurrentCulture, "CurrentCulture");
1300 Assert.IsNotNull (Thread.CurrentThread.CurrentUICulture, "CurrentUICulture");
1304 public void ThreadStartSimple ()
1307 Thread t = new Thread (delegate () {
1308 // ensure the NSAutoreleasePool works
1313 Assert.AreEqual (1, i, "ThreadStart");
1317 public void ParametrizedThreadStart ()
1321 Thread t = new Thread (delegate (object obj) {
1322 // ensure the NSAutoreleasePool works
1329 Assert.AreEqual (1, i, "ParametrizedThreadStart");
1330 Assert.AreEqual (this, arg, "obj");
1334 public void SetNameTpThread () {
1335 ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
1338 static void ThreadProc(Object stateInfo) {
1339 Thread.CurrentThread.Name = "My Worker";
1343 public void GetStackTraces () {
1344 var m = typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static);
1346 var res = (Dictionary<Thread,SD.StackTrace>)typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static).Invoke (null, null);
1347 foreach (var t in res.Keys) {
1348 var st = res [t].ToString ();
1354 public class TestUtil
1356 public static void WaitForNotAlive (Thread t, string s)
1358 WhileAlive (t, true, s);
1361 public static void WaitForAlive (Thread t, string s)
1363 WhileAlive (t, false, s);
1366 public static bool WaitForAliveOrStop (Thread t, string s)
1368 return WhileAliveOrStop (t, false, s);
1371 public static void WhileAlive (Thread t, bool alive, string s)
1373 DateTime ti = DateTime.Now;
1374 while (t.IsAlive == alive) {
1375 if ((DateTime.Now - ti).TotalSeconds > 10) {
1376 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1377 else Assert.Fail ("Timeout while waiting for alive state. " + s);
1382 public static bool WhileAliveOrStop (Thread t, bool alive, string s)
1384 DateTime ti = DateTime.Now;
1385 while (t.IsAlive == alive) {
1386 if (t.ThreadState == ThreadState.Stopped)
1389 if ((DateTime.Now - ti).TotalSeconds > 10) {
1390 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1391 else Assert.Fail ("Timeout while waiting for alive state. " + s);