Timeout.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Xunit;
  9. namespace Tests
  10. {
  11. public class Timeout : AsyncEnumerableExTests
  12. {
  13. [Fact]
  14. public async Task Timeout_Never()
  15. {
  16. var source = AsyncEnumerableEx.Never<int>().Timeout(TimeSpan.FromMilliseconds(100));
  17. var en = source.GetAsyncEnumerator();
  18. try
  19. {
  20. await en.MoveNextAsync();
  21. Assert.False(true, "MoveNextAsync should have thrown");
  22. }
  23. catch (TimeoutException)
  24. {
  25. // expected
  26. }
  27. finally
  28. {
  29. await en.DisposeAsync();
  30. }
  31. }
  32. [Fact]
  33. public async Task Timeout_Delayed_Main()
  34. {
  35. var source = AsyncEnumerable.Range(1, 5)
  36. .SelectAwait(async v =>
  37. {
  38. await Task.Delay(300);
  39. return v;
  40. })
  41. .Timeout(TimeSpan.FromMilliseconds(100));
  42. var en = source.GetAsyncEnumerator();
  43. try
  44. {
  45. await en.MoveNextAsync();
  46. Assert.False(true, "MoveNextAsync should have thrown");
  47. }
  48. catch (TimeoutException)
  49. {
  50. // expected
  51. }
  52. finally
  53. {
  54. await en.DisposeAsync();
  55. }
  56. }
  57. [Fact]
  58. public async Task Timeout_Delayed_Main_Canceled()
  59. {
  60. var tcs = new TaskCompletionSource<int>();
  61. var source = AsyncEnumerable.Range(1, 5)
  62. .SelectAwaitWithCancellation(async (v, ct) =>
  63. {
  64. try
  65. {
  66. await Task.Delay(500, ct);
  67. }
  68. catch (TaskCanceledException)
  69. {
  70. tcs.SetResult(0);
  71. }
  72. return v;
  73. })
  74. .Timeout(TimeSpan.FromMilliseconds(250));
  75. var en = source.GetAsyncEnumerator();
  76. try
  77. {
  78. await en.MoveNextAsync();
  79. Assert.False(true, "MoveNextAsync should have thrown");
  80. }
  81. catch (TimeoutException)
  82. {
  83. // expected
  84. }
  85. finally
  86. {
  87. await en.DisposeAsync();
  88. }
  89. Assert.Equal(0, await tcs.Task);
  90. }
  91. }
  92. }