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 ("System.MonoType", false) != null)
116 //Some Classes to test as threads
120 public Thread thread1;
126 thread1 = (Thread)null;
128 endm1 = endm2 = false;
131 public void TestMethod()
139 public void TestMethod2()
141 if (!(thread1==(Thread)null) )
152 public bool run = false;
159 public void TestMethod()
174 public C1Test sub_class;
175 public Thread sub_thread;
179 sub_class = new C1Test();
180 sub_thread = new Thread(new ThreadStart(sub_class.TestMethod));
183 public void TestMethod1()
193 public C1Test class1;
194 public C1Test class2;
195 public Thread thread1;
196 public Thread thread2;
204 class1 = new C1Test();
205 class2 = new C1Test();
206 thread1 = new Thread(new ThreadStart(class1.TestMethod));
207 thread2 = new Thread(new ThreadStart(class2.TestMethod));
210 public void TestMethod1()
213 TestUtil.WaitForAlive (thread1, "wait1");
216 TestUtil.WaitForAlive (thread2, "wait2");
219 TestUtil.WaitForNotAlive (thread1, "wait3");
222 TestUtil.WaitForNotAlive (thread2, "wait4");
226 public void TestMethod2()
234 public void TestCtor1()
236 C1Test test1 = new C1Test();
237 Thread t = new Thread (new ThreadStart (test1.TestMethod));
239 Assert.IsTrue (t.CurrentCulture.IsReadOnly, "CurrentCulture.IsReadOnly");
240 Assert.IsFalse (t.IsAlive, "IsAlive");
241 Assert.IsFalse (t.IsBackground, "IsBackground");
242 Assert.IsNull (t.Name, "Name");
243 Assert.AreEqual (ThreadState.Unstarted, t.ThreadState, "ThreadState");
247 [Category ("NotWorking")] // we're not sharing (read-only) CultureInfo
248 public void CultureInfo_Shared_Across_Threads ()
250 Thread t = new Thread (TestCtor1);
251 Assert.AreSame (t.CurrentCulture, t.CurrentUICulture, "Culture");
253 Assert.AreSame (t.CurrentCulture, CultureInfo.CurrentCulture, "CultureInfo.CurrentCulture");
254 Assert.AreSame (t.CurrentUICulture, CultureInfo.CurrentUICulture, "CultureInfo.CurrentUICulture");
256 Assert.AreSame (t.CurrentCulture, Thread.CurrentThread.CurrentCulture, "Thread.CurrentThread.CurrentCulture");
257 Assert.AreSame (t.CurrentUICulture, Thread.CurrentThread.CurrentUICulture, "Thread.CurrentThread.CurrentUICulture");
260 [Test] // bug #325566
261 public void GetHashCodeTest ()
263 C1Test test1 = new C1Test ();
264 Thread tA = new Thread (new ThreadStart (test1.TestMethod));
265 int hA1 = tA.GetHashCode ();
266 Assert.IsTrue (hA1 > 0, "#A1");
268 int hA2 = tA.GetHashCode ();
269 Assert.AreEqual (hA1, hA2, "#A2");
271 int hA3 = tA.GetHashCode ();
272 Assert.AreEqual (hA1, hA3, "#A3");
273 Assert.AreEqual (hA1, tA.ManagedThreadId, "#A4");
275 test1 = new C1Test ();
276 Thread tB = new Thread (new ThreadStart (test1.TestMethod));
277 int hB1 = tB.GetHashCode ();
278 Assert.IsTrue (hB1 > 0, "#B1");
280 int hB2 = tB.GetHashCode ();
281 Assert.AreEqual (hB1, hB2, "#B2");
283 int hB3 = tB.GetHashCode ();
284 Assert.AreEqual (hB1, hB3, "#B3");
285 Assert.AreEqual (hB1, tB.ManagedThreadId, "#B4");
286 Assert.IsFalse (hA2 == hB2, "#B5");
290 public void ManagedThreadId ()
292 C1Test test1 = new C1Test ();
293 Thread t1 = new Thread (new ThreadStart (test1.TestMethod));
294 int mtA1 = t1.ManagedThreadId;
296 int mtA2 = t1.ManagedThreadId;
298 int mtA3 = t1.ManagedThreadId;
299 Assert.AreEqual (mtA1, mtA2, "#A1");
300 Assert.AreEqual (mtA2, mtA3, "#A2");
302 test1 = new C1Test ();
303 Thread t2 = new Thread (new ThreadStart (test1.TestMethod));
304 int mtB1 = t2.ManagedThreadId;
306 int mtB2 = t2.ManagedThreadId;
308 int mtB3 = t2.ManagedThreadId;
309 Assert.AreEqual (mtB1, mtB2, "#B1");
310 Assert.AreEqual (mtB2, mtB3, "#B2");
311 Assert.IsFalse (mtB1 == mtA1, "#B3");
315 [Category ("NotDotNet")] // it hangs.
316 public void TestStart()
318 if (is_win32 && is_mono)
319 Assert.Fail ("This test fails on Win32. The test should be fixed.");
321 C1Test test1 = new C1Test();
322 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
325 Assert.AreEqual (10, test1.cnt, "#1");
328 C2Test test1 = new C2Test();
329 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
335 } catch (ThreadStateException) {
339 C2Test test1 = new C2Test();
340 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
344 bool started = (TestThread.ThreadState == ThreadState.Running);
345 Assert.AreEqual (started, test1.run, "#15 Thread Is not in the correct state: ");
351 public void TestApartmentState ()
353 if (is_win32 && is_mono)
354 Assert.Fail ("This test fails on mono on win32. Our runtime should be fixed.");
356 C2Test test1 = new C2Test();
357 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
358 Assert.AreEqual (ApartmentState.Unknown, TestThread.ApartmentState, "#1");
360 TestUtil.WaitForAlive (TestThread, "wait5");
361 Assert.AreEqual (ApartmentState.MTA, TestThread.ApartmentState, "#2");
366 public void TestPriority1()
368 if (is_win32 && is_mono)
369 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
371 C2Test test1 = new C2Test();
372 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
374 TestThread.Priority=ThreadPriority.BelowNormal;
375 ThreadPriority after = TestThread.Priority;
377 TestUtil.WaitForAlive (TestThread, "wait7");
378 ThreadPriority before = TestThread.Priority;
379 Assert.AreEqual (before, after, "#41 Unexpected Priority Change: ");
386 [Category ("NotDotNet")] // on MS, Thread is still in AbortRequested state when Start is invoked
387 public void AbortUnstarted ()
389 C2Test test1 = new C2Test();
390 Thread th = new Thread (new ThreadStart (test1.TestMethod));
396 [Category ("NotDotNet")] // on MS, ThreadState is immediately Stopped after Abort
397 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
398 public void TestPriority2()
400 C2Test test1 = new C2Test();
401 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
403 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#42 Incorrect Priority in New thread: ");
405 TestUtil.WaitForAliveOrStop (TestThread, "wait8");
406 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#43 Incorrect Priority in Started thread: ");
410 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#44 Incorrect Priority in Aborted thread: ");
414 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
415 public void TestPriority3()
417 C2Test test1 = new C2Test();
418 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
421 TestThread.Priority = ThreadPriority.Lowest;
422 Assert.AreEqual (ThreadPriority.Lowest, TestThread.Priority, "#45A Incorrect Priority:");
423 TestThread.Priority = ThreadPriority.BelowNormal;
424 Assert.AreEqual (ThreadPriority.BelowNormal, TestThread.Priority, "#45B Incorrect Priority:");
425 TestThread.Priority = ThreadPriority.Normal;
426 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#45C Incorrect Priority:");
427 TestThread.Priority = ThreadPriority.AboveNormal;
428 Assert.AreEqual (ThreadPriority.AboveNormal, TestThread.Priority, "#45D Incorrect Priority:");
429 TestThread.Priority = ThreadPriority.Highest;
430 Assert.AreEqual (ThreadPriority.Highest, TestThread.Priority, "#45E Incorrect Priority:");
438 public void TestUndivisibleByPageSizeMaxStackSize ()
440 const int undivisible_stacksize = 1048573;
442 var thread = new Thread (new ThreadStart (delegate {}), undivisible_stacksize);
448 public void TestIsBackground1 ()
450 if (is_win32 && is_mono)
451 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
453 C2Test test1 = new C2Test();
454 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
457 TestUtil.WaitForAlive (TestThread, "wait9");
458 bool state = TestThread.IsBackground;
459 Assert.IsFalse (state, "#51 IsBackground not set at the default state: ");
466 public void TestIsBackground2 ()
468 C2Test test1 = new C2Test();
469 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
470 TestThread.IsBackground = true;
477 if (TestThread.IsAlive) {
479 Assert.IsTrue (TestThread.IsBackground, "#52 Is Background Changed to Start ");
480 } catch (ThreadStateException) {
481 // Ignore if thread died meantime
487 public void TestName()
489 if (is_win32 && is_mono)
490 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
492 C2Test test1 = new C2Test();
493 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
496 TestUtil.WaitForAlive (TestThread, "wait10");
497 string name = TestThread.Name;
498 Assert.IsNull (name, "#61 Name set when mustn't be set: ");
499 string newname = "Testing....";
500 TestThread.Name = newname;
501 Assert.AreEqual (newname, TestThread.Name, "#62 Name not set when must be set: ");
510 Thread t = new Thread (new ThreadStart (Name));
511 Assert.IsNull (t.Name, "Name-1");
513 Assert.IsNull (t.Name, "Name-2");
517 [ExpectedException (typeof (InvalidOperationException))]
518 public void Rename ()
520 Thread t = new Thread (new ThreadStart (Rename));
525 bool rename_finished;
529 public void RenameTpThread ()
531 object monitor = new object ();
532 ThreadPool.QueueUserWorkItem (new WaitCallback (Rename_callback), monitor);
534 if (!rename_finished)
535 Monitor.Wait (monitor);
537 Assert.IsTrue (!rename_failed);
540 void Rename_callback (object o) {
541 Thread.CurrentThread.Name = "a";
543 Thread.CurrentThread.Name = "b";
544 //Console.WriteLine ("Thread name is: {0}", Thread.CurrentThread.Name);
545 } catch (Exception e) {
546 //Console.Error.WriteLine (e);
547 rename_failed = true;
551 rename_finished = true;
552 Monitor.Pulse (monitor);
557 public void TestNestedThreads1()
559 C3Test test1 = new C3Test();
560 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
563 TestUtil.WaitForAlive (TestThread, "wait11");
570 public void TestNestedThreads2()
572 C4Test test1 = new C4Test();
573 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
582 public void TestJoin1()
584 C1Test test1 = new C1Test();
585 C1Test test2 = new C1Test();
586 Thread thread1 = new Thread(new ThreadStart(test1.TestMethod));
587 Thread thread2 = new Thread(new ThreadStart(test1.TestMethod2));
599 [ExpectedException (typeof (ArgumentOutOfRangeException))]
600 public void Join_Int32_Negative ()
602 // -1 is Timeout.Infinite
603 Thread.CurrentThread.Join (-2);
607 [ExpectedException (typeof (ArgumentOutOfRangeException))]
608 public void Join_TimeSpan_Negative ()
610 Thread.CurrentThread.Join (Negative);
614 [ExpectedException (typeof (ArgumentOutOfRangeException))]
615 public void Join_TimeSpan_TooLarge ()
617 Thread.CurrentThread.Join (TooLarge);
621 public void Join_TimeSpan_SmallNegative ()
623 Thread.CurrentThread.Join (SmallNegative);
627 [ExpectedException (typeof (ArgumentOutOfRangeException))]
628 public void Sleep_Int32_Negative ()
630 // -1 is Timeout.Infinite
635 public void Sleep_TimeSpan_SmallNegative ()
637 Thread.Sleep (SmallNegative);
641 [ExpectedException (typeof (ArgumentOutOfRangeException))]
642 public void Sleep_TimeSpan_Negative ()
644 Thread.Sleep (Negative);
648 [ExpectedException (typeof (ArgumentOutOfRangeException))]
649 public void Sleep_TimeSpan_TooLarge ()
651 Thread.Sleep (TooLarge);
655 public void SpinWait ()
657 // no exception for negative numbers
658 Thread.SpinWait (Int32.MinValue);
663 public void TestThreadState ()
665 if (is_win32 && is_mono)
666 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
668 //TODO: Test The rest of the possible transitions
669 C2Test test1 = new C2Test();
670 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
671 Assert.AreEqual (ThreadState.Unstarted, TestThread.ThreadState, "#101 Wrong Thread State");
674 //while(!TestThread.IsAlive); //In the MS Documentation this is not necessary
675 //but in the MS SDK it is
676 Assert.IsTrue (TestThread.ThreadState == ThreadState.Running || (TestThread.ThreadState & ThreadState.Unstarted) != 0,
677 "#102 Wrong Thread State: " + TestThread.ThreadState.ToString ());
682 TestUtil.WaitForNotAlive (TestThread, "wait12");
683 // Docs say state will be Stopped, but Aborted happens sometimes (?)
684 Assert.IsTrue ((ThreadState.Stopped & TestThread.ThreadState) != 0 || (ThreadState.Aborted & TestThread.ThreadState) != 0,
685 "#103 Wrong Thread State: " + TestThread.ThreadState.ToString ());
689 [Ignore ("see comment below.")]
690 public void CurrentPrincipal_PrincipalPolicy_NoPrincipal ()
692 // note: switching from PrincipalPolicy won't work inside the same thread
693 // because as soon as a Principal object is created the Policy doesn't matter anymore
694 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.NoPrincipal));
704 [Ignore ("see comment below.")]
705 public void CurrentPrincipal_PrincipalPolicy_UnauthenticatedPrincipal ()
707 // note: switching from PrincipalPolicy won't work inside the same thread
708 // because as soon as a Principal object is created the Policy doesn't matter anymore
709 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.UnauthenticatedPrincipal));
719 public void CurrentPrincipal_PrincipalPolicy_WindowsPrincipal ()
721 // note: switching from PrincipalPolicy won't work inside the same thread
722 // because as soon as a Principal object is created the Policy doesn't matter anymore
723 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.WindowsPrincipal));
733 public void IPrincipal_CopyOnNewThread ()
735 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("bad"), null);
736 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.CopyOnNewThread));
738 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("good"), null);
749 public void TestSuspend ()
751 Thread t = new Thread (new ThreadStart (DoCount));
752 t.IsBackground = true;
755 CheckIsRunning ("t1", t);
758 WaitSuspended ("t2", t);
760 CheckIsNotRunning ("t3", t);
763 WaitResumed ("t4", t);
765 CheckIsRunning ("t5", t);
768 TestUtil.WaitForNotAlive (t, "wait13");
769 CheckIsNotRunning ("t6", t);
773 [Category("NotDotNet")] // On MS, ThreadStateException is thrown on Abort: "Thread is suspended; attempting to abort"
774 public void TestSuspendAbort ()
776 if (is_win32 && is_mono)
777 Assert.Fail ("This test fails on Win32. The test should be fixed.");
779 Thread t = new Thread (new ThreadStart (DoCount));
780 t.IsBackground = true;
783 CheckIsRunning ("t1", t);
786 WaitSuspended ("t2", t);
788 CheckIsNotRunning ("t3", t);
793 while (t.IsAlive && n < 200) {
798 Assert.IsTrue (n < 200, "Timeout while waiting for abort");
800 CheckIsNotRunning ("t6", t);
804 public void Test_Interrupt ()
806 ManualResetEvent mre = new ManualResetEvent (false);
807 bool interruptedExceptionThrown = false;
809 ThreadPool.QueueUserWorkItem (Test_Interrupt_Worker, Thread.CurrentThread);
817 } catch (ThreadInterruptedException) {
818 Assert.Fail ("ThreadInterruptedException thrown twice");
821 } catch (ThreadInterruptedException) {
822 interruptedExceptionThrown = true;
825 Assert.IsTrue (interruptedExceptionThrown, "ThreadInterruptedException expected.");
829 [ExpectedException (typeof (ArgumentNullException))]
830 public void TestQueueUserWorkItemNullCallback ()
832 ThreadPool.QueueUserWorkItem (null, null);
835 private void Test_Interrupt_Worker (object o)
837 Thread t = o as Thread;
843 [Category ("NotDotNet")] // it crashes nunit.
844 public void Test_InterruptCurrentThread ()
846 ManualResetEvent mre = new ManualResetEvent (false);
847 bool interruptedExceptionThrown = false;
849 Thread.CurrentThread.Interrupt ();
853 } catch (ThreadInterruptedException) {
858 public void GetNamedDataSlotTest ()
860 Assert.IsNotNull (Thread.GetNamedDataSlot ("te#st"), "#1");
861 Assert.AreSame (Thread.GetNamedDataSlot ("te#st"), Thread.GetNamedDataSlot ("te#st"), "#2");
864 class DomainClass : MarshalByRefObject {
869 m_thread = new Thread(ThreadProc);
870 m_thread.Start(Thread.CurrentThread);
875 public void ThreadProc (object arg) {
876 success = m_thread == Thread.CurrentThread;
881 public void CurrentThread_Domains ()
883 AppDomain ad = AppDomain.CreateDomain ("foo");
884 ad.Load (typeof (DomainClass).Assembly.GetName ());
885 var o = (DomainClass)ad.CreateInstanceAndUnwrap (typeof (DomainClass).Assembly.FullName, typeof (DomainClass).FullName);
886 Assert.IsTrue (o.Run ());
887 AppDomain.Unload (ad);
890 void CheckIsRunning (string s, Thread t)
894 Assert.IsTrue (counter > c, s);
897 void CheckIsNotRunning (string s, Thread t)
901 Assert.AreEqual (counter, c, s);
904 void WaitSuspended (string s, Thread t)
907 ThreadState state = t.ThreadState;
908 while ((state & ThreadState.Suspended) == 0) {
909 Assert.IsTrue ((state & ThreadState.SuspendRequested) != 0, s + ": expected SuspendRequested state");
912 Assert.IsTrue (n < 100, s + ": failed to suspend");
913 state = t.ThreadState;
915 Assert.IsTrue ((state & ThreadState.SuspendRequested) == 0, s + ": SuspendRequested state not expected");
918 void WaitResumed (string s, Thread t)
921 while ((t.ThreadState & ThreadState.Suspended) != 0) {
924 Assert.IsTrue (n < 100, s + ": failed to resume");
928 public void DoCount ()
938 public class ThreadStateTest {
944 public void IsBackGround ()
946 Thread t1 = new Thread (new ThreadStart (Start));
947 Assert.AreEqual (ThreadState.Unstarted, t1.ThreadState, "#A1");
948 Assert.IsFalse (t1.IsBackground, "#A2");
951 Assert.AreEqual (ThreadState.Stopped, t1.ThreadState, "#A3");
954 bool isBackGround = t1.IsBackground;
955 Assert.Fail ("#A4: " + isBackGround.ToString ());
956 } catch (ThreadStateException ex) {
957 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A5");
958 Assert.IsNull (ex.InnerException, "#A6");
959 Assert.IsNotNull (ex.Message, "#A7");
962 Thread t2 = new Thread (new ThreadStart (Start));
963 Assert.AreEqual (ThreadState.Unstarted, t2.ThreadState, "#B1");
964 t2.IsBackground = true;
965 Assert.AreEqual (ThreadState.Unstarted | ThreadState.Background, t2.ThreadState, "#B2");
966 Assert.IsTrue (t2.IsBackground, "#B3");
969 Assert.AreEqual (ThreadState.Stopped, t2.ThreadState, "#B4");
972 bool isBackGround = t2.IsBackground;
973 Assert.Fail ("#B5: " + isBackGround.ToString ());
974 } catch (ThreadStateException ex) {
975 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B6");
976 Assert.IsNull (ex.InnerException, "#B7");
977 Assert.IsNotNull (ex.Message, "#B8");
984 public class ThreadTest_ManagedThreadId
988 MBRO mbro = new MBRO ();
990 class MBRO : MarshalByRefObject {
997 public string message;
1001 public void ManagedThreadId_AppDomains ()
1003 AppDomain currentDomain = AppDomain.CurrentDomain;
1004 ad1 = AppDomain.CreateDomain ("AppDomain 1", currentDomain.Evidence, currentDomain.SetupInformation);
1005 ad2 = AppDomain.CreateDomain ("AppDomain 2", currentDomain.Evidence, currentDomain.SetupInformation);
1007 Thread a = new Thread (ThreadA);
1008 Thread b = new Thread (ThreadB);
1009 // execute on AppDomain 1 thread A
1010 // execute on AppDomain 2 thread B
1011 // execute on AppDomain 1 thread B - must have same ManagedThreadId as Ad 2 on thread B
1017 AppDomain.Unload (ad1);
1018 AppDomain.Unload (ad2);
1020 if (mbro.message != null)
1021 Assert.Fail (mbro.message);
1023 // 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);
1025 Assert.AreEqual ("AppDomain 1", mbro.ad_a1, "Name #1");
1026 Assert.AreEqual ("AppDomain 1", mbro.ad_b1, "Name #2");
1027 Assert.AreEqual ("AppDomain 2", mbro.ad_b2, "Name #3");
1029 Assert.AreNotEqual (mbro.id_a1, mbro.id_b1, "Id #1");
1030 Assert.AreNotEqual (mbro.id_a1, mbro.id_b2, "Id #2");
1031 Assert.AreEqual (mbro.id_b1, mbro.id_b2, "Id #3");
1033 Assert.AreNotEqual (mbro.id_a1, Thread.CurrentThread.ManagedThreadId, "Id #4");
1034 Assert.AreNotEqual (mbro.id_b1, Thread.CurrentThread.ManagedThreadId, "Id #5");
1035 Assert.AreNotEqual (mbro.id_b2, Thread.CurrentThread.ManagedThreadId, "Id #6");
1036 Assert.AreNotEqual (mbro.ad_a1, AppDomain.CurrentDomain.FriendlyName, "Name #4");
1037 Assert.AreNotEqual (mbro.ad_b1, AppDomain.CurrentDomain.FriendlyName, "Name #5");
1038 Assert.AreNotEqual (mbro.ad_b2, AppDomain.CurrentDomain.FriendlyName, "Name #6");
1043 mbro.id_a1 = Thread.CurrentThread.ManagedThreadId;
1044 mbro.ad_a1 = AppDomain.CurrentDomain.FriendlyName;
1049 mbro.id_b2 = Thread.CurrentThread.ManagedThreadId;
1050 mbro.ad_b2 = AppDomain.CurrentDomain.FriendlyName;
1055 mbro.id_b1 = Thread.CurrentThread.ManagedThreadId;
1056 mbro.ad_b1 = AppDomain.CurrentDomain.FriendlyName;
1059 void ThreadA (object obj)
1061 // Console.WriteLine ("ThreadA");
1063 ad1.DoCallBack (A1);
1064 } catch (Exception ex) {
1065 mbro.message = string.Format ("ThreadA exception: {0}", ex);
1067 // Console.WriteLine ("ThreadA Done");
1070 void ThreadB (object obj)
1072 // Console.WriteLine ("ThreadB");
1074 ad2.DoCallBack (B2);
1075 ad1.DoCallBack (B1);
1076 } catch (Exception ex) {
1077 mbro.message = string.Format ("ThreadB exception: {0}", ex);
1079 // Console.WriteLine ("ThreadB Done");
1084 public class ThreadApartmentTest
1090 [Test] // bug #81658
1091 public void ApartmentState_StoppedThread ()
1093 Thread t1 = new Thread (new ThreadStart (Start));
1097 ApartmentState state = t1.ApartmentState;
1098 Assert.Fail ("#A1: " + state.ToString ());
1099 } catch (ThreadStateException ex) {
1100 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A2");
1101 Assert.IsNull (ex.InnerException, "#A3");
1102 Assert.IsNotNull (ex.Message, "#A4");
1105 Thread t2 = new Thread (new ThreadStart (Start));
1106 t2.IsBackground = true;
1110 ApartmentState state = t2.ApartmentState;
1111 Assert.Fail ("#B1: " + state.ToString ());
1112 } catch (ThreadStateException ex) {
1113 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B2");
1114 Assert.IsNull (ex.InnerException, "#B3");
1115 Assert.IsNotNull (ex.Message, "#B4");
1120 public void ApartmentState_BackGround ()
1122 Thread t1 = new Thread (new ThreadStart (Start));
1123 t1.IsBackground = true;
1124 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "#1");
1125 t1.ApartmentState = ApartmentState.STA;
1126 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#2");
1130 public void TestApartmentState ()
1132 Thread t1 = new Thread (new ThreadStart (Start));
1133 Thread t2 = new Thread (new ThreadStart (Start));
1134 Thread t3 = new Thread (new ThreadStart (Start));
1136 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "Thread1 Default");
1137 Assert.AreEqual (ApartmentState.Unknown, t2.ApartmentState, "Thread2 Default");
1138 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Default");
1140 t1.ApartmentState = ApartmentState.STA;
1141 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1142 t1.ApartmentState = ApartmentState.MTA;
1143 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Twice");
1145 t2.ApartmentState = ApartmentState.MTA;
1146 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Once");
1147 t2.ApartmentState = ApartmentState.STA;
1148 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Twice");
1150 bool exception_occured = false;
1152 t3.ApartmentState = ApartmentState.Unknown;
1155 exception_occured = true;
1157 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Set Invalid");
1158 Assert.IsFalse (exception_occured, "Thread3 Set Invalid Exception Occured");
1161 exception_occured = false;
1163 t1.ApartmentState = ApartmentState.STA;
1166 exception_occured = true;
1168 Assert.IsTrue (exception_occured, "Thread1 Started Invalid Exception Occured");
1172 public void TestSetApartmentStateSameState ()
1174 Thread t1 = new Thread (new ThreadStart (Start));
1175 t1.SetApartmentState (ApartmentState.STA);
1176 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1178 t1.SetApartmentState (ApartmentState.STA);
1179 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set twice");
1183 [ExpectedException(typeof(InvalidOperationException))]
1184 public void TestSetApartmentStateDiffState ()
1186 Thread t1 = new Thread (new ThreadStart (Start));
1187 t1.SetApartmentState (ApartmentState.STA);
1188 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1190 t1.SetApartmentState (ApartmentState.MTA);
1194 public void TestTrySetApartmentState ()
1196 Thread t1 = new Thread (new ThreadStart (Start));
1197 t1.SetApartmentState (ApartmentState.STA);
1198 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1200 bool result = t1.TrySetApartmentState (ApartmentState.MTA);
1201 Assert.IsFalse (result, "#2");
1203 result = t1.TrySetApartmentState (ApartmentState.STA);
1204 Assert.IsTrue (result, "#3");
1208 public void TestTrySetApartmentStateRunning ()
1210 Thread t1 = new Thread (new ThreadStart (Start));
1211 t1.SetApartmentState (ApartmentState.STA);
1212 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1217 t1.TrySetApartmentState (ApartmentState.STA);
1219 } catch (ThreadStateException) {
1226 public void Volatile () {
1228 Thread.VolatileWrite (ref v3, double.MaxValue);
1229 Assert.AreEqual (v3, double.MaxValue);
1232 Thread.VolatileWrite (ref v4, float.MaxValue);
1233 Assert.AreEqual (v4, float.MaxValue);
1237 public void Culture ()
1239 Assert.IsNotNull (Thread.CurrentThread.CurrentCulture, "CurrentCulture");
1240 Assert.IsNotNull (Thread.CurrentThread.CurrentUICulture, "CurrentUICulture");
1244 public void ThreadStartSimple ()
1247 Thread t = new Thread (delegate () {
1248 // ensure the NSAutoreleasePool works
1253 Assert.AreEqual (1, i, "ThreadStart");
1257 public void ParametrizedThreadStart ()
1261 Thread t = new Thread (delegate (object obj) {
1262 // ensure the NSAutoreleasePool works
1269 Assert.AreEqual (1, i, "ParametrizedThreadStart");
1270 Assert.AreEqual (this, arg, "obj");
1274 public void SetNameTpThread () {
1275 ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
1278 static void ThreadProc(Object stateInfo) {
1279 Thread.CurrentThread.Name = "My Worker";
1283 public void GetStackTraces () {
1284 var m = typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static);
1286 var res = (Dictionary<Thread,SD.StackTrace>)typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static).Invoke (null, null);
1287 foreach (var t in res.Keys) {
1288 var st = res [t].ToString ();
1294 public class TestUtil
1296 public static void WaitForNotAlive (Thread t, string s)
1298 WhileAlive (t, true, s);
1301 public static void WaitForAlive (Thread t, string s)
1303 WhileAlive (t, false, s);
1306 public static bool WaitForAliveOrStop (Thread t, string s)
1308 return WhileAliveOrStop (t, false, s);
1311 public static void WhileAlive (Thread t, bool alive, string s)
1313 DateTime ti = DateTime.Now;
1314 while (t.IsAlive == alive) {
1315 if ((DateTime.Now - ti).TotalSeconds > 10) {
1316 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1317 else Assert.Fail ("Timeout while waiting for alive state. " + s);
1322 public static bool WhileAliveOrStop (Thread t, bool alive, string s)
1324 DateTime ti = DateTime.Now;
1325 while (t.IsAlive == alive) {
1326 if (t.ThreadState == ThreadState.Stopped)
1329 if ((DateTime.Now - ti).TotalSeconds > 10) {
1330 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1331 else Assert.Fail ("Timeout while waiting for alive state. " + s);