AsyncLockTest.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. #if !SILVERLIGHT // MethodAccessException
  3. using System;
  4. using System.Threading.Tasks;
  5. using System.Reactive.Concurrency;
  6. using System.Reflection;
  7. using Xunit;
  8. namespace ReactiveTests.Tests
  9. {
  10. public class AsyncLockTest
  11. {
  12. [Fact]
  13. public void Wait_ArgumentChecking()
  14. {
  15. var asyncLock = new AsyncLock();
  16. Assert.Throws<ArgumentNullException>(() => asyncLock.Wait(null));
  17. }
  18. [Fact]
  19. public void Wait_Graceful()
  20. {
  21. var ok = false;
  22. new AsyncLock().Wait(() => { ok = true; });
  23. Assert.True(ok);
  24. }
  25. [Fact]
  26. public void Wait_Fail()
  27. {
  28. var l = new AsyncLock();
  29. var ex = new Exception();
  30. try
  31. {
  32. l.Wait(() => { throw ex; });
  33. Assert.True(false);
  34. }
  35. catch (Exception e)
  36. {
  37. Assert.Same(ex, e);
  38. }
  39. // has faulted; should not run
  40. l.Wait(() => { Assert.True(false); });
  41. }
  42. [Fact]
  43. public void Wait_QueuesWork()
  44. {
  45. var l = new AsyncLock();
  46. var l1 = false;
  47. var l2 = false;
  48. l.Wait(() => { l.Wait(() => { Assert.True(l1); l2 = true; }); l1 = true; });
  49. Assert.True(l2);
  50. }
  51. [Fact]
  52. public void Dispose()
  53. {
  54. var l = new AsyncLock();
  55. var l1 = false;
  56. var l2 = false;
  57. var l3 = false;
  58. var l4 = false;
  59. l.Wait(() =>
  60. {
  61. l.Wait(() =>
  62. {
  63. l.Wait(() =>
  64. {
  65. l3 = true;
  66. });
  67. l2 = true;
  68. l.Dispose();
  69. l.Wait(() =>
  70. {
  71. l4 = true;
  72. });
  73. });
  74. l1 = true;
  75. });
  76. Assert.True(l1);
  77. Assert.True(l2);
  78. Assert.False(l3);
  79. Assert.False(l4);
  80. }
  81. public class AsyncLock
  82. {
  83. object instance;
  84. public AsyncLock()
  85. {
  86. instance = typeof(Scheduler).GetTypeInfo().Assembly.GetType("System.Reactive.Concurrency.AsyncLock").GetConstructor(new Type[] { }).Invoke(new object[] { });
  87. }
  88. public void Wait(Action action)
  89. {
  90. try
  91. {
  92. instance.GetType().GetMethod("Wait").Invoke(instance, new object[] { action });
  93. }
  94. catch (TargetInvocationException ex)
  95. {
  96. throw ex.InnerException;
  97. }
  98. }
  99. public void Dispose()
  100. {
  101. try
  102. {
  103. instance.GetType().GetMethod("Dispose").Invoke(instance, new object[0]);
  104. }
  105. catch (TargetInvocationException ex)
  106. {
  107. throw ex.InnerException;
  108. }
  109. }
  110. }
  111. }
  112. }
  113. #endif