AsyncLockTest.cs 2.3 KB

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