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 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 void CheckIsRunning (string s, Thread t)
868 Assert.IsTrue (counter > c, s);
871 void CheckIsNotRunning (string s, Thread t)
875 Assert.AreEqual (counter, c, s);
878 void WaitSuspended (string s, Thread t)
881 ThreadState state = t.ThreadState;
882 while ((state & ThreadState.Suspended) == 0) {
883 Assert.IsTrue ((state & ThreadState.SuspendRequested) != 0, s + ": expected SuspendRequested state");
886 Assert.IsTrue (n < 100, s + ": failed to suspend");
887 state = t.ThreadState;
889 Assert.IsTrue ((state & ThreadState.SuspendRequested) == 0, s + ": SuspendRequested state not expected");
892 void WaitResumed (string s, Thread t)
895 while ((t.ThreadState & ThreadState.Suspended) != 0) {
898 Assert.IsTrue (n < 100, s + ": failed to resume");
902 public void DoCount ()
912 public class ThreadStateTest {
918 public void IsBackGround ()
920 Thread t1 = new Thread (new ThreadStart (Start));
921 Assert.AreEqual (ThreadState.Unstarted, t1.ThreadState, "#A1");
922 Assert.IsFalse (t1.IsBackground, "#A2");
925 Assert.AreEqual (ThreadState.Stopped, t1.ThreadState, "#A3");
928 bool isBackGround = t1.IsBackground;
929 Assert.Fail ("#A4: " + isBackGround.ToString ());
930 } catch (ThreadStateException ex) {
931 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A5");
932 Assert.IsNull (ex.InnerException, "#A6");
933 Assert.IsNotNull (ex.Message, "#A7");
936 Thread t2 = new Thread (new ThreadStart (Start));
937 Assert.AreEqual (ThreadState.Unstarted, t2.ThreadState, "#B1");
938 t2.IsBackground = true;
939 Assert.AreEqual (ThreadState.Unstarted | ThreadState.Background, t2.ThreadState, "#B2");
940 Assert.IsTrue (t2.IsBackground, "#B3");
943 Assert.AreEqual (ThreadState.Stopped, t2.ThreadState, "#B4");
946 bool isBackGround = t2.IsBackground;
947 Assert.Fail ("#B5: " + isBackGround.ToString ());
948 } catch (ThreadStateException ex) {
949 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B6");
950 Assert.IsNull (ex.InnerException, "#B7");
951 Assert.IsNotNull (ex.Message, "#B8");
958 public class ThreadTest_ManagedThreadId
962 MBRO mbro = new MBRO ();
964 class MBRO : MarshalByRefObject {
971 public string message;
975 public void ManagedThreadId_AppDomains ()
977 AppDomain currentDomain = AppDomain.CurrentDomain;
978 ad1 = AppDomain.CreateDomain ("AppDomain 1", currentDomain.Evidence, currentDomain.SetupInformation);
979 ad2 = AppDomain.CreateDomain ("AppDomain 2", currentDomain.Evidence, currentDomain.SetupInformation);
981 Thread a = new Thread (ThreadA);
982 Thread b = new Thread (ThreadB);
983 // execute on AppDomain 1 thread A
984 // execute on AppDomain 2 thread B
985 // execute on AppDomain 1 thread B - must have same ManagedThreadId as Ad 2 on thread B
991 AppDomain.Unload (ad1);
992 AppDomain.Unload (ad2);
994 if (mbro.message != null)
995 Assert.Fail (mbro.message);
997 // 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);
999 Assert.AreEqual ("AppDomain 1", mbro.ad_a1, "Name #1");
1000 Assert.AreEqual ("AppDomain 1", mbro.ad_b1, "Name #2");
1001 Assert.AreEqual ("AppDomain 2", mbro.ad_b2, "Name #3");
1003 Assert.AreNotEqual (mbro.id_a1, mbro.id_b1, "Id #1");
1004 Assert.AreNotEqual (mbro.id_a1, mbro.id_b2, "Id #2");
1005 Assert.AreEqual (mbro.id_b1, mbro.id_b2, "Id #3");
1007 Assert.AreNotEqual (mbro.id_a1, Thread.CurrentThread.ManagedThreadId, "Id #4");
1008 Assert.AreNotEqual (mbro.id_b1, Thread.CurrentThread.ManagedThreadId, "Id #5");
1009 Assert.AreNotEqual (mbro.id_b2, Thread.CurrentThread.ManagedThreadId, "Id #6");
1010 Assert.AreNotEqual (mbro.ad_a1, AppDomain.CurrentDomain.FriendlyName, "Name #4");
1011 Assert.AreNotEqual (mbro.ad_b1, AppDomain.CurrentDomain.FriendlyName, "Name #5");
1012 Assert.AreNotEqual (mbro.ad_b2, AppDomain.CurrentDomain.FriendlyName, "Name #6");
1017 mbro.id_a1 = Thread.CurrentThread.ManagedThreadId;
1018 mbro.ad_a1 = AppDomain.CurrentDomain.FriendlyName;
1023 mbro.id_b2 = Thread.CurrentThread.ManagedThreadId;
1024 mbro.ad_b2 = AppDomain.CurrentDomain.FriendlyName;
1029 mbro.id_b1 = Thread.CurrentThread.ManagedThreadId;
1030 mbro.ad_b1 = AppDomain.CurrentDomain.FriendlyName;
1033 void ThreadA (object obj)
1035 // Console.WriteLine ("ThreadA");
1037 ad1.DoCallBack (A1);
1038 } catch (Exception ex) {
1039 mbro.message = string.Format ("ThreadA exception: {0}", ex);
1041 // Console.WriteLine ("ThreadA Done");
1044 void ThreadB (object obj)
1046 // Console.WriteLine ("ThreadB");
1048 ad2.DoCallBack (B2);
1049 ad1.DoCallBack (B1);
1050 } catch (Exception ex) {
1051 mbro.message = string.Format ("ThreadB exception: {0}", ex);
1053 // Console.WriteLine ("ThreadB Done");
1058 public class ThreadApartmentTest
1064 [Test] // bug #81658
1065 public void ApartmentState_StoppedThread ()
1067 Thread t1 = new Thread (new ThreadStart (Start));
1071 ApartmentState state = t1.ApartmentState;
1072 Assert.Fail ("#A1: " + state.ToString ());
1073 } catch (ThreadStateException ex) {
1074 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A2");
1075 Assert.IsNull (ex.InnerException, "#A3");
1076 Assert.IsNotNull (ex.Message, "#A4");
1079 Thread t2 = new Thread (new ThreadStart (Start));
1080 t2.IsBackground = true;
1084 ApartmentState state = t2.ApartmentState;
1085 Assert.Fail ("#B1: " + state.ToString ());
1086 } catch (ThreadStateException ex) {
1087 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B2");
1088 Assert.IsNull (ex.InnerException, "#B3");
1089 Assert.IsNotNull (ex.Message, "#B4");
1094 public void ApartmentState_BackGround ()
1096 Thread t1 = new Thread (new ThreadStart (Start));
1097 t1.IsBackground = true;
1098 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "#1");
1099 t1.ApartmentState = ApartmentState.STA;
1100 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#2");
1104 public void TestApartmentState ()
1106 Thread t1 = new Thread (new ThreadStart (Start));
1107 Thread t2 = new Thread (new ThreadStart (Start));
1108 Thread t3 = new Thread (new ThreadStart (Start));
1110 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "Thread1 Default");
1111 Assert.AreEqual (ApartmentState.Unknown, t2.ApartmentState, "Thread2 Default");
1112 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Default");
1114 t1.ApartmentState = ApartmentState.STA;
1115 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1116 t1.ApartmentState = ApartmentState.MTA;
1117 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Twice");
1119 t2.ApartmentState = ApartmentState.MTA;
1120 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Once");
1121 t2.ApartmentState = ApartmentState.STA;
1122 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Twice");
1124 bool exception_occured = false;
1126 t3.ApartmentState = ApartmentState.Unknown;
1129 exception_occured = true;
1131 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Set Invalid");
1132 Assert.IsFalse (exception_occured, "Thread3 Set Invalid Exception Occured");
1135 exception_occured = false;
1137 t1.ApartmentState = ApartmentState.STA;
1140 exception_occured = true;
1142 Assert.IsTrue (exception_occured, "Thread1 Started Invalid Exception Occured");
1146 public void TestSetApartmentStateSameState ()
1148 Thread t1 = new Thread (new ThreadStart (Start));
1149 t1.SetApartmentState (ApartmentState.STA);
1150 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1152 t1.SetApartmentState (ApartmentState.STA);
1153 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set twice");
1157 [ExpectedException(typeof(InvalidOperationException))]
1158 public void TestSetApartmentStateDiffState ()
1160 Thread t1 = new Thread (new ThreadStart (Start));
1161 t1.SetApartmentState (ApartmentState.STA);
1162 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1164 t1.SetApartmentState (ApartmentState.MTA);
1168 public void TestTrySetApartmentState ()
1170 Thread t1 = new Thread (new ThreadStart (Start));
1171 t1.SetApartmentState (ApartmentState.STA);
1172 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1174 bool result = t1.TrySetApartmentState (ApartmentState.MTA);
1175 Assert.IsFalse (result, "#2");
1177 result = t1.TrySetApartmentState (ApartmentState.STA);
1178 Assert.IsTrue (result, "#3");
1182 public void TestTrySetApartmentStateRunning ()
1184 Thread t1 = new Thread (new ThreadStart (Start));
1185 t1.SetApartmentState (ApartmentState.STA);
1186 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1191 t1.TrySetApartmentState (ApartmentState.STA);
1193 } catch (ThreadStateException) {
1200 public void Volatile () {
1202 Thread.VolatileWrite (ref v3, double.MaxValue);
1203 Assert.AreEqual (v3, double.MaxValue);
1206 Thread.VolatileWrite (ref v4, float.MaxValue);
1207 Assert.AreEqual (v4, float.MaxValue);
1211 public void Culture ()
1213 Assert.IsNotNull (Thread.CurrentThread.CurrentCulture, "CurrentCulture");
1214 Assert.IsNotNull (Thread.CurrentThread.CurrentUICulture, "CurrentUICulture");
1218 public void ThreadStartSimple ()
1221 Thread t = new Thread (delegate () {
1222 // ensure the NSAutoreleasePool works
1227 Assert.AreEqual (1, i, "ThreadStart");
1231 public void ParametrizedThreadStart ()
1235 Thread t = new Thread (delegate (object obj) {
1236 // ensure the NSAutoreleasePool works
1243 Assert.AreEqual (1, i, "ParametrizedThreadStart");
1244 Assert.AreEqual (this, arg, "obj");
1248 public void SetNameTpThread () {
1249 ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
1252 static void ThreadProc(Object stateInfo) {
1253 Thread.CurrentThread.Name = "My Worker";
1257 public void GetStackTraces () {
1258 var m = typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static);
1260 var res = (Dictionary<Thread,StackTrace>)typeof (Thread).GetMethod ("Mono_GetStackTraces", BindingFlags.NonPublic|BindingFlags.Static).Invoke (null, null);
1261 foreach (var t in res.Keys) {
1262 var st = res [t].ToString ();
1268 public class TestUtil
1270 public static void WaitForNotAlive (Thread t, string s)
1272 WhileAlive (t, true, s);
1275 public static void WaitForAlive (Thread t, string s)
1277 WhileAlive (t, false, s);
1280 public static bool WaitForAliveOrStop (Thread t, string s)
1282 return WhileAliveOrStop (t, false, s);
1285 public static void WhileAlive (Thread t, bool alive, string s)
1287 DateTime ti = DateTime.Now;
1288 while (t.IsAlive == alive) {
1289 if ((DateTime.Now - ti).TotalSeconds > 10) {
1290 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1291 else Assert.Fail ("Timeout while waiting for alive state. " + s);
1296 public static bool WhileAliveOrStop (Thread t, bool alive, string s)
1298 DateTime ti = DateTime.Now;
1299 while (t.IsAlive == alive) {
1300 if (t.ThreadState == ThreadState.Stopped)
1303 if ((DateTime.Now - ti).TotalSeconds > 10) {
1304 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1305 else Assert.Fail ("Timeout while waiting for alive state. " + s);