ConcurrencyTest.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Reactive.Concurrency;
  6. using System.Threading;
  7. using Microsoft.VisualStudio.TestTools.UnitTesting;
  8. using Assert = Xunit.Assert;
  9. namespace ReactiveTests.Tests
  10. {
  11. [TestClass]
  12. public class ConcurrencyTest
  13. {
  14. [TestMethod]
  15. public void CurrentScheduler_EnsureTrampoline()
  16. {
  17. const int concurrency = 100;
  18. var passed = true;
  19. var s = new Semaphore(0, int.MaxValue);
  20. var e = new ManualResetEvent(false);
  21. for (var i = 0; i < concurrency; ++i)
  22. {
  23. NewThreadScheduler.Default.Schedule(() =>
  24. {
  25. e.WaitOne();
  26. try
  27. {
  28. if (Scheduler.CurrentThread.ScheduleRequired)
  29. {
  30. Scheduler.CurrentThread.Schedule(() => { });
  31. }
  32. else
  33. {
  34. new Action(() => { })();
  35. }
  36. }
  37. catch (NullReferenceException)
  38. {
  39. passed = false;
  40. }
  41. finally
  42. {
  43. s.Release();
  44. }
  45. });
  46. }
  47. e.Set();
  48. for (var i = 0; i < concurrency; ++i)
  49. {
  50. s.WaitOne();
  51. }
  52. Assert.True(passed);
  53. }
  54. [TestMethod]
  55. public void CurrentScheduler_Schedule()
  56. {
  57. const int concurrency = 100;
  58. var passed = true;
  59. var s = new Semaphore(0, int.MaxValue);
  60. var e = new ManualResetEvent(false);
  61. for (var i = 0; i < concurrency; ++i)
  62. {
  63. NewThreadScheduler.Default.Schedule(() =>
  64. {
  65. e.WaitOne();
  66. try
  67. {
  68. if (Scheduler.CurrentThread.ScheduleRequired)
  69. {
  70. Scheduler.CurrentThread.Schedule(() => { });
  71. }
  72. else
  73. {
  74. new Action(() => { })();
  75. }
  76. }
  77. catch (NullReferenceException)
  78. {
  79. passed = false;
  80. }
  81. finally
  82. {
  83. s.Release();
  84. }
  85. });
  86. }
  87. e.Set();
  88. for (var i = 0; i < concurrency; ++i)
  89. {
  90. s.WaitOne();
  91. }
  92. Assert.True(passed);
  93. }
  94. }
  95. }