AsyncLockTest.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 Xunit;
  7. namespace ReactiveTests.Tests
  8. {
  9. public class AsyncLockTest
  10. {
  11. [Fact]
  12. public void Wait_ArgumentChecking()
  13. {
  14. var asyncLock = new AsyncLock();
  15. Assert.Throws<ArgumentNullException>(() => asyncLock.Wait(null));
  16. }
  17. [Fact]
  18. public void Wait_Graceful()
  19. {
  20. var ok = false;
  21. new AsyncLock().Wait(() => { ok = true; });
  22. Assert.True(ok);
  23. }
  24. [Fact]
  25. public void Wait_Fail()
  26. {
  27. var l = new AsyncLock();
  28. var ex = new Exception();
  29. try
  30. {
  31. l.Wait(() => { throw ex; });
  32. Assert.True(false);
  33. }
  34. catch (Exception e)
  35. {
  36. Assert.Same(ex, e);
  37. }
  38. // has faulted; should not run
  39. l.Wait(() => { Assert.True(false); });
  40. }
  41. [Fact]
  42. public void Wait_QueuesWork()
  43. {
  44. var l = new AsyncLock();
  45. var l1 = false;
  46. var l2 = false;
  47. l.Wait(() => { l.Wait(() => { Assert.True(l1); l2 = true; }); l1 = true; });
  48. Assert.True(l2);
  49. }
  50. [Fact]
  51. public void Dispose()
  52. {
  53. var l = new AsyncLock();
  54. var l1 = false;
  55. var l2 = false;
  56. var l3 = false;
  57. var l4 = false;
  58. l.Wait(() =>
  59. {
  60. l.Wait(() =>
  61. {
  62. l.Wait(() =>
  63. {
  64. l3 = true;
  65. });
  66. l2 = true;
  67. l.Dispose();
  68. l.Wait(() =>
  69. {
  70. l4 = true;
  71. });
  72. });
  73. l1 = true;
  74. });
  75. Assert.True(l1);
  76. Assert.True(l2);
  77. Assert.False(l3);
  78. Assert.False(l4);
  79. }
  80. }
  81. }