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;
17 using NUnit.Framework;
19 namespace MonoTests.System.Threading
21 // These tests seem to hang the 2.0 framework. So they are disabled for now
22 // Don't reenable them until you can run a few thousand times on an SMP box.
23 [Category ("NotWorking")]
24 public class ThreadedPrincipalTest
26 public static void NoPrincipal ()
28 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.NoPrincipal);
29 IPrincipal p = Thread.CurrentPrincipal;
30 Assert.IsNull (p, "#1");
32 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
33 Assert.IsNotNull (Thread.CurrentPrincipal, "#2");
35 Thread.CurrentPrincipal = null;
36 Assert.IsNull (Thread.CurrentPrincipal, "#3");
37 // in this case we can return to null
40 public static void UnauthenticatedPrincipal ()
42 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.UnauthenticatedPrincipal);
43 IPrincipal p = Thread.CurrentPrincipal;
44 Assert.IsNotNull (p, "#1");
45 Assert.IsTrue ((p is GenericPrincipal), "#2");
46 Assert.AreEqual (String.Empty, p.Identity.Name, "#3");
47 Assert.AreEqual (String.Empty, p.Identity.AuthenticationType, "#4");
48 Assert.IsFalse (p.Identity.IsAuthenticated, "#5");
50 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
51 Assert.IsNotNull (Thread.CurrentPrincipal, "#6");
53 Thread.CurrentPrincipal = null;
54 Assert.IsNotNull (Thread.CurrentPrincipal, "#7");
55 // in this case we can't return to null
58 public static void WindowsPrincipal ()
60 AppDomain.CurrentDomain.SetPrincipalPolicy (PrincipalPolicy.WindowsPrincipal);
61 IPrincipal p = Thread.CurrentPrincipal;
62 Assert.IsNotNull (p, "#1");
63 Assert.IsTrue ((p is WindowsPrincipal), "#2");
64 Assert.IsNotNull (p.Identity.Name, "#3");
65 Assert.IsNotNull (p.Identity.AuthenticationType, "#4");
66 Assert.IsTrue (p.Identity.IsAuthenticated, "#5");
68 // note: we can switch from a WindowsPrincipal to a GenericPrincipal
69 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("mono"), null);
70 Assert.IsNotNull (Thread.CurrentPrincipal, "#6");
72 Thread.CurrentPrincipal = null;
73 Assert.IsNotNull (Thread.CurrentPrincipal, "#7");
74 // in this case we can't return to null
77 public static void CopyOnNewThread ()
79 Assert.IsNotNull (Thread.CurrentPrincipal, "#1");
80 Assert.AreEqual ("good", Thread.CurrentPrincipal.Identity.Name, "#2");
85 [Category("MobileNotWorking")] // Abort #10240
86 public class ThreadTest
88 //TimeSpan Infinite = new TimeSpan (-10000); // -10000 ticks == -1 ms
89 TimeSpan SmallNegative = new TimeSpan (-2); // between 0 and -1.0 (infinite) ms
90 TimeSpan Negative = new TimeSpan (-20000); // really negative
91 //TimeSpan MaxValue = TimeSpan.FromMilliseconds ((long) Int32.MaxValue);
92 TimeSpan TooLarge = TimeSpan.FromMilliseconds ((long) Int32.MaxValue + 1);
99 switch (Environment.OSVersion.Platform) {
100 case PlatformID.Win32NT:
101 case PlatformID.Win32S:
102 case PlatformID.Win32Windows:
103 case PlatformID.WinCE:
108 // check a class in mscorlib to determine if we're running on Mono
109 if (Type.GetType ("System.MonoType", false) != null)
113 //Some Classes to test as threads
117 public Thread thread1;
123 thread1 = (Thread)null;
125 endm1 = endm2 = false;
128 public void TestMethod()
136 public void TestMethod2()
138 if (!(thread1==(Thread)null) )
149 public bool run = false;
156 public void TestMethod()
171 public C1Test sub_class;
172 public Thread sub_thread;
176 sub_class = new C1Test();
177 sub_thread = new Thread(new ThreadStart(sub_class.TestMethod));
180 public void TestMethod1()
190 public C1Test class1;
191 public C1Test class2;
192 public Thread thread1;
193 public Thread thread2;
201 class1 = new C1Test();
202 class2 = new C1Test();
203 thread1 = new Thread(new ThreadStart(class1.TestMethod));
204 thread2 = new Thread(new ThreadStart(class2.TestMethod));
207 public void TestMethod1()
210 TestUtil.WaitForAlive (thread1, "wait1");
213 TestUtil.WaitForAlive (thread2, "wait2");
216 TestUtil.WaitForNotAlive (thread1, "wait3");
219 TestUtil.WaitForNotAlive (thread2, "wait4");
223 public void TestMethod2()
231 public void TestCtor1()
233 C1Test test1 = new C1Test();
234 Thread t = new Thread (new ThreadStart (test1.TestMethod));
236 Assert.IsTrue (t.CurrentCulture.IsReadOnly, "CurrentCulture.IsReadOnly");
237 Assert.IsFalse (t.IsAlive, "IsAlive");
238 Assert.IsFalse (t.IsBackground, "IsBackground");
239 Assert.IsNull (t.Name, "Name");
240 Assert.AreEqual (ThreadState.Unstarted, t.ThreadState, "ThreadState");
244 [Category ("NotWorking")] // we're not sharing (read-only) CultureInfo
245 public void CultureInfo_Shared_Across_Threads ()
247 Thread t = new Thread (TestCtor1);
248 Assert.AreSame (t.CurrentCulture, t.CurrentUICulture, "Culture");
250 Assert.AreSame (t.CurrentCulture, CultureInfo.CurrentCulture, "CultureInfo.CurrentCulture");
251 Assert.AreSame (t.CurrentUICulture, CultureInfo.CurrentUICulture, "CultureInfo.CurrentUICulture");
253 Assert.AreSame (t.CurrentCulture, Thread.CurrentThread.CurrentCulture, "Thread.CurrentThread.CurrentCulture");
254 Assert.AreSame (t.CurrentUICulture, Thread.CurrentThread.CurrentUICulture, "Thread.CurrentThread.CurrentUICulture");
257 [Test] // bug #325566
258 public void GetHashCodeTest ()
260 C1Test test1 = new C1Test ();
261 Thread tA = new Thread (new ThreadStart (test1.TestMethod));
262 int hA1 = tA.GetHashCode ();
263 Assert.IsTrue (hA1 > 0, "#A1");
265 int hA2 = tA.GetHashCode ();
266 Assert.AreEqual (hA1, hA2, "#A2");
268 int hA3 = tA.GetHashCode ();
269 Assert.AreEqual (hA1, hA3, "#A3");
270 Assert.AreEqual (hA1, tA.ManagedThreadId, "#A4");
272 test1 = new C1Test ();
273 Thread tB = new Thread (new ThreadStart (test1.TestMethod));
274 int hB1 = tB.GetHashCode ();
275 Assert.IsTrue (hB1 > 0, "#B1");
277 int hB2 = tB.GetHashCode ();
278 Assert.AreEqual (hB1, hB2, "#B2");
280 int hB3 = tB.GetHashCode ();
281 Assert.AreEqual (hB1, hB3, "#B3");
282 Assert.AreEqual (hB1, tB.ManagedThreadId, "#B4");
283 Assert.IsFalse (hA2 == hB2, "#B5");
287 public void ManagedThreadId ()
289 C1Test test1 = new C1Test ();
290 Thread t1 = new Thread (new ThreadStart (test1.TestMethod));
291 int mtA1 = t1.ManagedThreadId;
293 int mtA2 = t1.ManagedThreadId;
295 int mtA3 = t1.ManagedThreadId;
296 Assert.AreEqual (mtA1, mtA2, "#A1");
297 Assert.AreEqual (mtA2, mtA3, "#A2");
299 test1 = new C1Test ();
300 Thread t2 = new Thread (new ThreadStart (test1.TestMethod));
301 int mtB1 = t2.ManagedThreadId;
303 int mtB2 = t2.ManagedThreadId;
305 int mtB3 = t2.ManagedThreadId;
306 Assert.AreEqual (mtB1, mtB2, "#B1");
307 Assert.AreEqual (mtB2, mtB3, "#B2");
308 Assert.IsFalse (mtB1 == mtA1, "#B3");
312 [Category ("NotDotNet")] // it hangs.
313 public void TestStart()
315 if (is_win32 && is_mono)
316 Assert.Fail ("This test fails on Win32. The test should be fixed.");
318 C1Test test1 = new C1Test();
319 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
322 Assert.AreEqual (10, test1.cnt, "#1");
325 C2Test test1 = new C2Test();
326 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
332 } catch (ThreadStateException) {
336 C2Test test1 = new C2Test();
337 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
341 bool started = (TestThread.ThreadState == ThreadState.Running);
342 Assert.AreEqual (started, test1.run, "#15 Thread Is not in the correct state: ");
348 public void TestApartmentState ()
350 if (is_win32 && is_mono)
351 Assert.Fail ("This test fails on mono on win32. Our runtime should be fixed.");
353 C2Test test1 = new C2Test();
354 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
355 Assert.AreEqual (ApartmentState.Unknown, TestThread.ApartmentState, "#1");
357 TestUtil.WaitForAlive (TestThread, "wait5");
358 Assert.AreEqual (ApartmentState.MTA, TestThread.ApartmentState, "#2");
363 public void TestPriority1()
365 if (is_win32 && is_mono)
366 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
368 C2Test test1 = new C2Test();
369 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
371 TestThread.Priority=ThreadPriority.BelowNormal;
372 ThreadPriority after = TestThread.Priority;
374 TestUtil.WaitForAlive (TestThread, "wait7");
375 ThreadPriority before = TestThread.Priority;
376 Assert.AreEqual (before, after, "#41 Unexpected Priority Change: ");
383 [Category ("NotDotNet")] // on MS, Thread is still in AbortRequested state when Start is invoked
384 public void AbortUnstarted ()
386 C2Test test1 = new C2Test();
387 Thread th = new Thread (new ThreadStart (test1.TestMethod));
393 [Category ("NotDotNet")] // on MS, ThreadState is immediately Stopped after Abort
394 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
395 public void TestPriority2()
397 C2Test test1 = new C2Test();
398 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
400 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#42 Incorrect Priority in New thread: ");
402 TestUtil.WaitForAliveOrStop (TestThread, "wait8");
403 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#43 Incorrect Priority in Started thread: ");
407 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#44 Incorrect Priority in Aborted thread: ");
411 [Category ("NotWorking")] // this is a MonoTODO -> no support for Priority
412 public void TestPriority3()
414 C2Test test1 = new C2Test();
415 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
418 TestThread.Priority = ThreadPriority.Lowest;
419 Assert.AreEqual (ThreadPriority.Lowest, TestThread.Priority, "#45A Incorrect Priority:");
420 TestThread.Priority = ThreadPriority.BelowNormal;
421 Assert.AreEqual (ThreadPriority.BelowNormal, TestThread.Priority, "#45B Incorrect Priority:");
422 TestThread.Priority = ThreadPriority.Normal;
423 Assert.AreEqual (ThreadPriority.Normal, TestThread.Priority, "#45C Incorrect Priority:");
424 TestThread.Priority = ThreadPriority.AboveNormal;
425 Assert.AreEqual (ThreadPriority.AboveNormal, TestThread.Priority, "#45D Incorrect Priority:");
426 TestThread.Priority = ThreadPriority.Highest;
427 Assert.AreEqual (ThreadPriority.Highest, TestThread.Priority, "#45E Incorrect Priority:");
435 public void TestUndivisibleByPageSizeMaxStackSize ()
437 const int undivisible_stacksize = 1048573;
439 var thread = new Thread (new ThreadStart (delegate {}), undivisible_stacksize);
445 public void TestIsBackground1 ()
447 if (is_win32 && is_mono)
448 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
450 C2Test test1 = new C2Test();
451 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
454 TestUtil.WaitForAlive (TestThread, "wait9");
455 bool state = TestThread.IsBackground;
456 Assert.IsFalse (state, "#51 IsBackground not set at the default state: ");
463 public void TestIsBackground2 ()
465 C2Test test1 = new C2Test();
466 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
467 TestThread.IsBackground = true;
474 if (TestThread.IsAlive) {
476 Assert.IsTrue (TestThread.IsBackground, "#52 Is Background Changed to Start ");
477 } catch (ThreadStateException) {
478 // Ignore if thread died meantime
484 public void TestName()
486 if (is_win32 && is_mono)
487 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
489 C2Test test1 = new C2Test();
490 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
493 TestUtil.WaitForAlive (TestThread, "wait10");
494 string name = TestThread.Name;
495 Assert.IsNull (name, "#61 Name set when mustn't be set: ");
496 string newname = "Testing....";
497 TestThread.Name = newname;
498 Assert.AreEqual (newname, TestThread.Name, "#62 Name not set when must be set: ");
507 Thread t = new Thread (new ThreadStart (Name));
508 Assert.IsNull (t.Name, "Name-1");
510 Assert.IsNull (t.Name, "Name-2");
514 [ExpectedException (typeof (InvalidOperationException))]
515 public void Rename ()
517 Thread t = new Thread (new ThreadStart (Rename));
522 bool rename_finished;
526 public void RenameTpThread ()
528 object monitor = new object ();
529 ThreadPool.QueueUserWorkItem (new WaitCallback (Rename_callback), monitor);
531 if (!rename_finished)
532 Monitor.Wait (monitor);
534 Assert.IsTrue (!rename_failed);
537 void Rename_callback (object o) {
538 Thread.CurrentThread.Name = "a";
540 Thread.CurrentThread.Name = "b";
541 //Console.WriteLine ("Thread name is: {0}", Thread.CurrentThread.Name);
542 } catch (Exception e) {
543 //Console.Error.WriteLine (e);
544 rename_failed = true;
548 rename_finished = true;
549 Monitor.Pulse (monitor);
554 public void TestNestedThreads1()
556 C3Test test1 = new C3Test();
557 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
560 TestUtil.WaitForAlive (TestThread, "wait11");
567 public void TestNestedThreads2()
569 C4Test test1 = new C4Test();
570 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod1));
579 public void TestJoin1()
581 C1Test test1 = new C1Test();
582 C1Test test2 = new C1Test();
583 Thread thread1 = new Thread(new ThreadStart(test1.TestMethod));
584 Thread thread2 = new Thread(new ThreadStart(test1.TestMethod2));
596 [ExpectedException (typeof (ArgumentOutOfRangeException))]
597 public void Join_Int32_Negative ()
599 // -1 is Timeout.Infinite
600 Thread.CurrentThread.Join (-2);
604 [ExpectedException (typeof (ArgumentOutOfRangeException))]
605 public void Join_TimeSpan_Negative ()
607 Thread.CurrentThread.Join (Negative);
611 [ExpectedException (typeof (ArgumentOutOfRangeException))]
612 public void Join_TimeSpan_TooLarge ()
614 Thread.CurrentThread.Join (TooLarge);
618 public void Join_TimeSpan_SmallNegative ()
620 Thread.CurrentThread.Join (SmallNegative);
624 [ExpectedException (typeof (ArgumentOutOfRangeException))]
625 public void Sleep_Int32_Negative ()
627 // -1 is Timeout.Infinite
632 public void Sleep_TimeSpan_SmallNegative ()
634 Thread.Sleep (SmallNegative);
638 [ExpectedException (typeof (ArgumentOutOfRangeException))]
639 public void Sleep_TimeSpan_Negative ()
641 Thread.Sleep (Negative);
645 [ExpectedException (typeof (ArgumentOutOfRangeException))]
646 public void Sleep_TimeSpan_TooLarge ()
648 Thread.Sleep (TooLarge);
652 public void SpinWait ()
654 // no exception for negative numbers
655 Thread.SpinWait (Int32.MinValue);
660 public void TestThreadState ()
662 if (is_win32 && is_mono)
663 Assert.Fail ("This test fails on mono on Win32. Our runtime should be fixed.");
665 //TODO: Test The rest of the possible transitions
666 C2Test test1 = new C2Test();
667 Thread TestThread = new Thread(new ThreadStart(test1.TestMethod));
668 Assert.AreEqual (ThreadState.Unstarted, TestThread.ThreadState, "#101 Wrong Thread State");
671 //while(!TestThread.IsAlive); //In the MS Documentation this is not necessary
672 //but in the MS SDK it is
673 Assert.IsTrue (TestThread.ThreadState == ThreadState.Running || (TestThread.ThreadState & ThreadState.Unstarted) != 0,
674 "#102 Wrong Thread State: " + TestThread.ThreadState.ToString ());
679 TestUtil.WaitForNotAlive (TestThread, "wait12");
680 // Docs say state will be Stopped, but Aborted happens sometimes (?)
681 Assert.IsTrue ((ThreadState.Stopped & TestThread.ThreadState) != 0 || (ThreadState.Aborted & TestThread.ThreadState) != 0,
682 "#103 Wrong Thread State: " + TestThread.ThreadState.ToString ());
686 [Ignore ("see comment below.")]
687 public void CurrentPrincipal_PrincipalPolicy_NoPrincipal ()
689 // note: switching from PrincipalPolicy won't work inside the same thread
690 // because as soon as a Principal object is created the Policy doesn't matter anymore
691 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.NoPrincipal));
701 [Ignore ("see comment below.")]
702 public void CurrentPrincipal_PrincipalPolicy_UnauthenticatedPrincipal ()
704 // note: switching from PrincipalPolicy won't work inside the same thread
705 // because as soon as a Principal object is created the Policy doesn't matter anymore
706 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.UnauthenticatedPrincipal));
716 public void CurrentPrincipal_PrincipalPolicy_WindowsPrincipal ()
718 // note: switching from PrincipalPolicy won't work inside the same thread
719 // because as soon as a Principal object is created the Policy doesn't matter anymore
720 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.WindowsPrincipal));
730 public void IPrincipal_CopyOnNewThread ()
732 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("bad"), null);
733 Thread t = new Thread (new ThreadStart (ThreadedPrincipalTest.CopyOnNewThread));
735 Thread.CurrentPrincipal = new GenericPrincipal (new GenericIdentity ("good"), null);
746 public void TestSuspend ()
748 Thread t = new Thread (new ThreadStart (DoCount));
749 t.IsBackground = true;
752 CheckIsRunning ("t1", t);
755 WaitSuspended ("t2", t);
757 CheckIsNotRunning ("t3", t);
760 WaitResumed ("t4", t);
762 CheckIsRunning ("t5", t);
765 TestUtil.WaitForNotAlive (t, "wait13");
766 CheckIsNotRunning ("t6", t);
770 [Category("NotDotNet")] // On MS, ThreadStateException is thrown on Abort: "Thread is suspended; attempting to abort"
771 public void TestSuspendAbort ()
773 if (is_win32 && is_mono)
774 Assert.Fail ("This test fails on Win32. The test should be fixed.");
776 Thread t = new Thread (new ThreadStart (DoCount));
777 t.IsBackground = true;
780 CheckIsRunning ("t1", t);
783 WaitSuspended ("t2", t);
785 CheckIsNotRunning ("t3", t);
790 while (t.IsAlive && n < 200) {
795 Assert.IsTrue (n < 200, "Timeout while waiting for abort");
797 CheckIsNotRunning ("t6", t);
801 public void Test_Interrupt ()
803 bool interruptedExceptionThrown = false;
804 ThreadPool.QueueUserWorkItem (Test_Interrupt_Worker, Thread.CurrentThread);
812 } catch (ThreadInterruptedException) {
813 Assert.Fail ("ThreadInterruptedException thrown twice");
816 } catch (ThreadInterruptedException) {
817 interruptedExceptionThrown = true;
820 Assert.IsTrue (interruptedExceptionThrown, "ThreadInterruptedException expected.");
824 [ExpectedException (typeof (ArgumentNullException))]
825 public void TestQueueUserWorkItemNullCallback ()
827 ThreadPool.QueueUserWorkItem (null, null);
830 private void Test_Interrupt_Worker (object o)
832 Thread t = o as Thread;
838 [Category ("NotDotNet")] // it crashes nunit.
839 public void Test_InterruptCurrentThread ()
841 bool interruptedExceptionThrown = false;
843 Thread.CurrentThread.Interrupt ();
847 } catch (ThreadInterruptedException) {
852 public void GetNamedDataSlotTest ()
854 Assert.IsNotNull (Thread.GetNamedDataSlot ("te#st"), "#1");
855 Assert.AreSame (Thread.GetNamedDataSlot ("te#st"), Thread.GetNamedDataSlot ("te#st"), "#2");
858 void CheckIsRunning (string s, Thread t)
862 Assert.IsTrue (counter > c, s);
865 void CheckIsNotRunning (string s, Thread t)
869 Assert.AreEqual (counter, c, s);
872 void WaitSuspended (string s, Thread t)
875 ThreadState state = t.ThreadState;
876 while ((state & ThreadState.Suspended) == 0) {
877 Assert.IsTrue ((state & ThreadState.SuspendRequested) != 0, s + ": expected SuspendRequested state");
880 Assert.IsTrue (n < 100, s + ": failed to suspend");
881 state = t.ThreadState;
883 Assert.IsTrue ((state & ThreadState.SuspendRequested) == 0, s + ": SuspendRequested state not expected");
886 void WaitResumed (string s, Thread t)
889 while ((t.ThreadState & ThreadState.Suspended) != 0) {
892 Assert.IsTrue (n < 100, s + ": failed to resume");
896 public void DoCount ()
906 public class ThreadStateTest {
912 public void IsBackGround ()
914 Thread t1 = new Thread (new ThreadStart (Start));
915 Assert.AreEqual (ThreadState.Unstarted, t1.ThreadState, "#A1");
916 Assert.IsFalse (t1.IsBackground, "#A2");
919 Assert.AreEqual (ThreadState.Stopped, t1.ThreadState, "#A3");
922 bool isBackGround = t1.IsBackground;
923 Assert.Fail ("#A4: " + isBackGround.ToString ());
924 } catch (ThreadStateException ex) {
925 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A5");
926 Assert.IsNull (ex.InnerException, "#A6");
927 Assert.IsNotNull (ex.Message, "#A7");
930 Thread t2 = new Thread (new ThreadStart (Start));
931 Assert.AreEqual (ThreadState.Unstarted, t2.ThreadState, "#B1");
932 t2.IsBackground = true;
933 Assert.AreEqual (ThreadState.Unstarted | ThreadState.Background, t2.ThreadState, "#B2");
934 Assert.IsTrue (t2.IsBackground, "#B3");
937 Assert.AreEqual (ThreadState.Stopped, t2.ThreadState, "#B4");
940 bool isBackGround = t2.IsBackground;
941 Assert.Fail ("#B5: " + isBackGround.ToString ());
942 } catch (ThreadStateException ex) {
943 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B6");
944 Assert.IsNull (ex.InnerException, "#B7");
945 Assert.IsNotNull (ex.Message, "#B8");
952 public class ThreadTest_ManagedThreadId
956 MBRO mbro = new MBRO ();
958 class MBRO : MarshalByRefObject {
965 public string message;
969 public void ManagedThreadId_AppDomains ()
971 AppDomain currentDomain = AppDomain.CurrentDomain;
972 ad1 = AppDomain.CreateDomain ("AppDomain 1", currentDomain.Evidence, currentDomain.SetupInformation);
973 ad2 = AppDomain.CreateDomain ("AppDomain 2", currentDomain.Evidence, currentDomain.SetupInformation);
975 Thread a = new Thread (ThreadA);
976 Thread b = new Thread (ThreadB);
977 // execute on AppDomain 1 thread A
978 // execute on AppDomain 2 thread B
979 // execute on AppDomain 1 thread B - must have same ManagedThreadId as Ad 2 on thread B
985 AppDomain.Unload (ad1);
986 AppDomain.Unload (ad2);
988 if (mbro.message != null)
989 Assert.Fail (mbro.message);
991 // 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);
993 Assert.AreEqual ("AppDomain 1", mbro.ad_a1, "Name #1");
994 Assert.AreEqual ("AppDomain 1", mbro.ad_b1, "Name #2");
995 Assert.AreEqual ("AppDomain 2", mbro.ad_b2, "Name #3");
997 Assert.AreNotEqual (mbro.id_a1, mbro.id_b1, "Id #1");
998 Assert.AreNotEqual (mbro.id_a1, mbro.id_b2, "Id #2");
999 Assert.AreEqual (mbro.id_b1, mbro.id_b2, "Id #3");
1001 Assert.AreNotEqual (mbro.id_a1, Thread.CurrentThread.ManagedThreadId, "Id #4");
1002 Assert.AreNotEqual (mbro.id_b1, Thread.CurrentThread.ManagedThreadId, "Id #5");
1003 Assert.AreNotEqual (mbro.id_b2, Thread.CurrentThread.ManagedThreadId, "Id #6");
1004 Assert.AreNotEqual (mbro.ad_a1, AppDomain.CurrentDomain.FriendlyName, "Name #4");
1005 Assert.AreNotEqual (mbro.ad_b1, AppDomain.CurrentDomain.FriendlyName, "Name #5");
1006 Assert.AreNotEqual (mbro.ad_b2, AppDomain.CurrentDomain.FriendlyName, "Name #6");
1011 mbro.id_a1 = Thread.CurrentThread.ManagedThreadId;
1012 mbro.ad_a1 = AppDomain.CurrentDomain.FriendlyName;
1017 mbro.id_b2 = Thread.CurrentThread.ManagedThreadId;
1018 mbro.ad_b2 = AppDomain.CurrentDomain.FriendlyName;
1023 mbro.id_b1 = Thread.CurrentThread.ManagedThreadId;
1024 mbro.ad_b1 = AppDomain.CurrentDomain.FriendlyName;
1027 void ThreadA (object obj)
1029 // Console.WriteLine ("ThreadA");
1031 ad1.DoCallBack (A1);
1032 } catch (Exception ex) {
1033 mbro.message = string.Format ("ThreadA exception: {0}", ex);
1035 // Console.WriteLine ("ThreadA Done");
1038 void ThreadB (object obj)
1040 // Console.WriteLine ("ThreadB");
1042 ad2.DoCallBack (B2);
1043 ad1.DoCallBack (B1);
1044 } catch (Exception ex) {
1045 mbro.message = string.Format ("ThreadB exception: {0}", ex);
1047 // Console.WriteLine ("ThreadB Done");
1052 public class ThreadApartmentTest
1058 [Test] // bug #81658
1059 public void ApartmentState_StoppedThread ()
1061 Thread t1 = new Thread (new ThreadStart (Start));
1065 ApartmentState state = t1.ApartmentState;
1066 Assert.Fail ("#A1: " + state.ToString ());
1067 } catch (ThreadStateException ex) {
1068 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#A2");
1069 Assert.IsNull (ex.InnerException, "#A3");
1070 Assert.IsNotNull (ex.Message, "#A4");
1073 Thread t2 = new Thread (new ThreadStart (Start));
1074 t2.IsBackground = true;
1078 ApartmentState state = t2.ApartmentState;
1079 Assert.Fail ("#B1: " + state.ToString ());
1080 } catch (ThreadStateException ex) {
1081 Assert.AreEqual (typeof (ThreadStateException), ex.GetType (), "#B2");
1082 Assert.IsNull (ex.InnerException, "#B3");
1083 Assert.IsNotNull (ex.Message, "#B4");
1088 public void ApartmentState_BackGround ()
1090 Thread t1 = new Thread (new ThreadStart (Start));
1091 t1.IsBackground = true;
1092 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "#1");
1093 t1.ApartmentState = ApartmentState.STA;
1094 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#2");
1098 public void TestApartmentState ()
1100 Thread t1 = new Thread (new ThreadStart (Start));
1101 Thread t2 = new Thread (new ThreadStart (Start));
1102 Thread t3 = new Thread (new ThreadStart (Start));
1104 Assert.AreEqual (ApartmentState.Unknown, t1.ApartmentState, "Thread1 Default");
1105 Assert.AreEqual (ApartmentState.Unknown, t2.ApartmentState, "Thread2 Default");
1106 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Default");
1108 t1.ApartmentState = ApartmentState.STA;
1109 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1110 t1.ApartmentState = ApartmentState.MTA;
1111 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Twice");
1113 t2.ApartmentState = ApartmentState.MTA;
1114 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Once");
1115 t2.ApartmentState = ApartmentState.STA;
1116 Assert.AreEqual (ApartmentState.MTA, t2.ApartmentState, "Thread2 Set Twice");
1118 bool exception_occured = false;
1120 t3.ApartmentState = ApartmentState.Unknown;
1123 exception_occured = true;
1125 Assert.AreEqual (ApartmentState.Unknown, t3.ApartmentState, "Thread3 Set Invalid");
1126 Assert.IsFalse (exception_occured, "Thread3 Set Invalid Exception Occured");
1129 exception_occured = false;
1131 t1.ApartmentState = ApartmentState.STA;
1134 exception_occured = true;
1136 Assert.IsTrue (exception_occured, "Thread1 Started Invalid Exception Occured");
1140 public void TestSetApartmentStateSameState ()
1142 Thread t1 = new Thread (new ThreadStart (Start));
1143 t1.SetApartmentState (ApartmentState.STA);
1144 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1146 t1.SetApartmentState (ApartmentState.STA);
1147 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set twice");
1151 [ExpectedException(typeof(InvalidOperationException))]
1152 public void TestSetApartmentStateDiffState ()
1154 Thread t1 = new Thread (new ThreadStart (Start));
1155 t1.SetApartmentState (ApartmentState.STA);
1156 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "Thread1 Set Once");
1158 t1.SetApartmentState (ApartmentState.MTA);
1162 public void TestTrySetApartmentState ()
1164 Thread t1 = new Thread (new ThreadStart (Start));
1165 t1.SetApartmentState (ApartmentState.STA);
1166 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1168 bool result = t1.TrySetApartmentState (ApartmentState.MTA);
1169 Assert.IsFalse (result, "#2");
1171 result = t1.TrySetApartmentState (ApartmentState.STA);
1172 Assert.IsTrue (result, "#3");
1176 public void TestTrySetApartmentStateRunning ()
1178 Thread t1 = new Thread (new ThreadStart (Start));
1179 t1.SetApartmentState (ApartmentState.STA);
1180 Assert.AreEqual (ApartmentState.STA, t1.ApartmentState, "#1");
1185 t1.TrySetApartmentState (ApartmentState.STA);
1187 } catch (ThreadStateException) {
1194 public void Volatile () {
1196 Thread.VolatileWrite (ref v3, double.MaxValue);
1197 Assert.AreEqual (v3, double.MaxValue);
1200 Thread.VolatileWrite (ref v4, float.MaxValue);
1201 Assert.AreEqual (v4, float.MaxValue);
1205 public void Culture ()
1207 Assert.IsNotNull (Thread.CurrentThread.CurrentCulture, "CurrentCulture");
1208 Assert.IsNotNull (Thread.CurrentThread.CurrentUICulture, "CurrentUICulture");
1212 public void ThreadStartSimple ()
1215 Thread t = new Thread (delegate () {
1216 // ensure the NSAutoreleasePool works
1221 Assert.AreEqual (1, i, "ThreadStart");
1225 public void ParametrizedThreadStart ()
1229 Thread t = new Thread (delegate (object obj) {
1230 // ensure the NSAutoreleasePool works
1237 Assert.AreEqual (1, i, "ParametrizedThreadStart");
1238 Assert.AreEqual (this, arg, "obj");
1242 public void SetNameTpThread () {
1243 ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
1246 static void ThreadProc(Object stateInfo) {
1247 Thread.CurrentThread.Name = "My Worker";
1251 public class TestUtil
1253 public static void WaitForNotAlive (Thread t, string s)
1255 WhileAlive (t, true, s);
1258 public static void WaitForAlive (Thread t, string s)
1260 WhileAlive (t, false, s);
1263 public static bool WaitForAliveOrStop (Thread t, string s)
1265 return WhileAliveOrStop (t, false, s);
1268 public static void WhileAlive (Thread t, bool alive, string s)
1270 DateTime ti = DateTime.Now;
1271 while (t.IsAlive == alive) {
1272 if ((DateTime.Now - ti).TotalSeconds > 10) {
1273 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1274 else Assert.Fail ("Timeout while waiting for alive state. " + s);
1279 public static bool WhileAliveOrStop (Thread t, bool alive, string s)
1281 DateTime ti = DateTime.Now;
1282 while (t.IsAlive == alive) {
1283 if (t.ThreadState == ThreadState.Stopped)
1286 if ((DateTime.Now - ti).TotalSeconds > 10) {
1287 if (alive) Assert.Fail ("Timeout while waiting for not alive state. " + s);
1288 else Assert.Fail ("Timeout while waiting for alive state. " + s);