AsyncTests.Bugs.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using Xunit;
  9. using System.Collections;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Diagnostics;
  13. namespace Tests
  14. {
  15. public partial class AsyncTests
  16. {
  17. public AsyncTests()
  18. {
  19. TaskScheduler.UnobservedTaskException += (o, e) =>
  20. {
  21. };
  22. }
  23. /*
  24. [Fact]
  25. public void TestPushPopAsync()
  26. {
  27. var stack = new Stack<int>();
  28. var count = 10;
  29. var observable = Observable.Generate(
  30. 0,
  31. i => i < count,
  32. i => i + 1,
  33. i => i,
  34. i => TimeSpan.FromMilliseconds(1), // change this to 0 to avoid the problem [1]
  35. Scheduler.ThreadPool);
  36. var task = DoSomethingAsync(observable, stack);
  37. // we give it a timeout so the test can fail instead of hang
  38. task.Wait(TimeSpan.FromSeconds(2));
  39. Assert.Equal(10, stack.Count);
  40. }
  41. private Task DoSomethingAsync(IObservable<int> observable, Stack<int> stack)
  42. {
  43. var ae = observable
  44. .ToAsyncEnumerable()
  45. //.Do(i => Debug.WriteLine("Bug-fixing side effect: " + i)) // [2]
  46. .GetEnumerator();
  47. var tcs = new TaskCompletionSource<object>();
  48. var a = default(Action);
  49. a = new Action(() =>
  50. {
  51. ae.MoveNext().ContinueWith(t =>
  52. {
  53. if (t.Result)
  54. {
  55. var i = ae.Current;
  56. Debug.WriteLine("Doing something with " + i);
  57. Thread.Sleep(50);
  58. stack.Push(i);
  59. a();
  60. }
  61. else
  62. tcs.TrySetResult(null);
  63. });
  64. });
  65. a();
  66. return tcs.Task;
  67. }
  68. */
  69. #if !NO_THREAD
  70. static IEnumerable<int> Xs(Action a)
  71. {
  72. try
  73. {
  74. var rnd = new Random();
  75. while (true)
  76. {
  77. yield return rnd.Next(0, 43);
  78. Thread.Sleep(rnd.Next(0, 500));
  79. }
  80. }
  81. finally
  82. {
  83. a();
  84. }
  85. }
  86. #endif
  87. [Fact]
  88. public async void CorrectDispose()
  89. {
  90. var disposed = new TaskCompletionSource<bool>();
  91. var xs = new[] { 1, 2, 3 }.WithDispose(() =>
  92. {
  93. disposed.TrySetResult(true);
  94. }).ToAsyncEnumerable();
  95. var ys = xs.Select(x => x + 1);
  96. var e = ys.GetEnumerator();
  97. // We have to call move next because otherwise the internal enumerator is never allocated
  98. await e.MoveNext();
  99. e.Dispose();
  100. await disposed.Task;
  101. Assert.True(disposed.Task.Result);
  102. Assert.False(e.MoveNext().Result);
  103. var next = await e.MoveNext();
  104. Assert.False(next);
  105. }
  106. [Fact]
  107. public async Task DisposesUponError()
  108. {
  109. var disposed = new TaskCompletionSource<bool>();
  110. var xs = new[] { 1, 2, 3 }.WithDispose(() =>
  111. {
  112. disposed.SetResult(true);
  113. }).ToAsyncEnumerable();
  114. var ex = new Exception("Bang!");
  115. var ys = xs.Select(x => { if (x == 1) throw ex; return x; });
  116. var e = ys.GetEnumerator();
  117. await Assert.ThrowsAsync<Exception>(() => e.MoveNext());
  118. var result = await disposed.Task;
  119. Assert.True(result);
  120. }
  121. [Fact]
  122. public async Task CorrectCancel()
  123. {
  124. var disposed = new TaskCompletionSource<bool>();
  125. var xs = new CancellationTestAsyncEnumerable().WithDispose(() =>
  126. {
  127. disposed.TrySetResult(true);
  128. });
  129. var ys = xs.Select(x => x + 1).Where(x => true);
  130. var e = ys.GetEnumerator();
  131. var cts = new CancellationTokenSource();
  132. var t = e.MoveNext(cts.Token);
  133. cts.Cancel();
  134. try
  135. {
  136. t.Wait(WaitTimeoutMs);
  137. }
  138. catch
  139. {
  140. // Don't care about the outcome; we could have made it to element 1
  141. // but we could also have cancelled the MoveNext-calling task. Either
  142. // way, we want to wait for the task to be completed and check that
  143. }
  144. finally
  145. {
  146. // the cancellation bubbled all the way up to the source to dispose
  147. // it. This design is chosen because cancelling a MoveNext call leaves
  148. // the enumerator in an indeterminate state. Further interactions with
  149. // it should be forbidden.
  150. var result = await disposed.Task;
  151. Assert.True(result);
  152. }
  153. Assert.False(await e.MoveNext());
  154. }
  155. [Fact]
  156. public void CanCancelMoveNext()
  157. {
  158. var xs = new CancellationTestAsyncEnumerable().Select(x => x).Where(x => true);
  159. var e = xs.GetEnumerator();
  160. var cts = new CancellationTokenSource();
  161. var t = e.MoveNext(cts.Token);
  162. cts.Cancel();
  163. try
  164. {
  165. t.Wait(WaitTimeoutMs);
  166. Assert.True(false);
  167. }
  168. catch
  169. {
  170. Assert.True(t.IsCanceled);
  171. }
  172. }
  173. /// <summary>
  174. /// Waits WaitTimeoutMs or until cancellation is requested. If cancellation was not requested, MoveNext returns true.
  175. /// </summary>
  176. private sealed class CancellationTestAsyncEnumerable : IAsyncEnumerable<int>
  177. {
  178. private readonly int iterationsBeforeDelay;
  179. public CancellationTestAsyncEnumerable(int iterationsBeforeDelay = 0)
  180. {
  181. this.iterationsBeforeDelay = iterationsBeforeDelay;
  182. }
  183. public IAsyncEnumerator<int> GetEnumerator() => new TestEnumerator(iterationsBeforeDelay);
  184. private sealed class TestEnumerator : IAsyncEnumerator<int>
  185. {
  186. private readonly int iterationsBeforeDelay;
  187. public TestEnumerator(int iterationsBeforeDelay)
  188. {
  189. this.iterationsBeforeDelay = iterationsBeforeDelay;
  190. }
  191. int i = -1;
  192. public void Dispose()
  193. {
  194. }
  195. public int Current => i;
  196. public async Task<bool> MoveNext(CancellationToken cancellationToken)
  197. {
  198. i++;
  199. if (Current >= iterationsBeforeDelay)
  200. {
  201. await Task.Delay(WaitTimeoutMs, cancellationToken);
  202. }
  203. cancellationToken.ThrowIfCancellationRequested();
  204. return true;
  205. }
  206. }
  207. }
  208. /// <summary>
  209. /// Waits WaitTimeoutMs or until cancellation is requested. If cancellation was not requested, MoveNext returns true.
  210. /// </summary>
  211. private sealed class CancellationTestEnumerable<T> : IEnumerable<T>
  212. {
  213. public CancellationTestEnumerable()
  214. {
  215. }
  216. public IEnumerator<T> GetEnumerator() => new TestEnumerator();
  217. private sealed class TestEnumerator : IEnumerator<T>
  218. {
  219. private readonly CancellationTokenSource cancellationTokenSource;
  220. public TestEnumerator()
  221. {
  222. cancellationTokenSource = new CancellationTokenSource();
  223. }
  224. public void Dispose()
  225. {
  226. cancellationTokenSource.Cancel();
  227. }
  228. public void Reset()
  229. {
  230. }
  231. object IEnumerator.Current => Current;
  232. public T Current { get; }
  233. public bool MoveNext()
  234. {
  235. Task.Delay(WaitTimeoutMs, cancellationTokenSource.Token).Wait();
  236. cancellationTokenSource.Token.ThrowIfCancellationRequested();
  237. return true;
  238. }
  239. }
  240. IEnumerator IEnumerable.GetEnumerator()
  241. {
  242. return GetEnumerator();
  243. }
  244. }
  245. [Fact]
  246. public void ToAsyncEnumeratorCannotCancelOnceRunning()
  247. {
  248. var evt = new ManualResetEvent(false);
  249. var isRunningEvent = new ManualResetEvent(false);
  250. var xs = Blocking(evt, isRunningEvent).ToAsyncEnumerable();
  251. var e = xs.GetEnumerator();
  252. var cts = new CancellationTokenSource();
  253. Task<bool> t = null;
  254. var tMoveNext =Task.Run(
  255. () =>
  256. {
  257. // This call *will* block
  258. t = e.MoveNext(cts.Token);
  259. });
  260. isRunningEvent.WaitOne();
  261. cts.Cancel();
  262. try
  263. {
  264. tMoveNext.Wait(0);
  265. Assert.False(t.IsCanceled);
  266. }
  267. catch
  268. {
  269. // T will still be null
  270. Assert.Null(t);
  271. }
  272. // enable it to finish
  273. evt.Set();
  274. }
  275. static IEnumerable<int> Blocking(ManualResetEvent evt, ManualResetEvent blockingStarted)
  276. {
  277. blockingStarted.Set();
  278. evt.WaitOne();
  279. yield return 42;
  280. }
  281. [Fact]
  282. public async Task TakeOneFromSelectMany()
  283. {
  284. var enumerable = AsyncEnumerable
  285. .Return(0)
  286. .SelectMany(_ => AsyncEnumerable.Return("Check"))
  287. .Take(1)
  288. .Do(_ => { });
  289. Assert.Equal("Check", await enumerable.First());
  290. }
  291. [Fact]
  292. public void SelectManyDisposeInvokedOnlyOnce()
  293. {
  294. var disposeCounter = new DisposeCounter();
  295. var result = AsyncEnumerable.Return(1).SelectMany(i => disposeCounter).Select(i => i).ToList().Result;
  296. Assert.Equal(0, result.Count);
  297. Assert.Equal(1, disposeCounter.DisposeCount);
  298. }
  299. [Fact]
  300. public void SelectManyInnerDispose()
  301. {
  302. var disposes = Enumerable.Range(0, 10).Select(_ => new DisposeCounter()).ToList();
  303. var result = AsyncEnumerable.Range(0, 10).SelectMany(i => disposes[i]).Select(i => i).ToList().Result;
  304. Assert.Equal(0, result.Count);
  305. Assert.True(disposes.All(d => d.DisposeCount == 1));
  306. }
  307. [Fact]
  308. public void DisposeAfterCreation()
  309. {
  310. var enumerable = AsyncEnumerable.Return(0) as IDisposable;
  311. enumerable?.Dispose();
  312. }
  313. private class DisposeCounter : IAsyncEnumerable<object>
  314. {
  315. public int DisposeCount { get; private set; }
  316. public IAsyncEnumerator<object> GetEnumerator()
  317. {
  318. return new Enumerator(this);
  319. }
  320. private class Enumerator : IAsyncEnumerator<object>
  321. {
  322. private readonly DisposeCounter _disposeCounter;
  323. public Enumerator(DisposeCounter disposeCounter)
  324. {
  325. _disposeCounter = disposeCounter;
  326. }
  327. public void Dispose()
  328. {
  329. _disposeCounter.DisposeCount++;
  330. }
  331. public Task<bool> MoveNext(CancellationToken _)
  332. {
  333. return Task.Factory.StartNew(() => false);
  334. }
  335. public object Current { get; private set; }
  336. }
  337. }
  338. }
  339. static class MyExt
  340. {
  341. public static IEnumerable<T> WithDispose<T>(this IEnumerable<T> source, Action a)
  342. {
  343. return EnumerableEx.Create(() =>
  344. {
  345. var e = source.GetEnumerator();
  346. return new Enumerator<T>(e.MoveNext, () => e.Current, () => { e.Dispose(); a(); });
  347. });
  348. }
  349. public static IAsyncEnumerable<T> WithDispose<T>(this IAsyncEnumerable<T> source, Action a)
  350. {
  351. return AsyncEnumerable.CreateEnumerable<T>(() =>
  352. {
  353. var e = source.GetEnumerator();
  354. return AsyncEnumerable.CreateEnumerator<T>(e.MoveNext, () => e.Current, () => { e.Dispose(); a(); });
  355. });
  356. }
  357. class Enumerator<T> : IEnumerator<T>
  358. {
  359. private readonly Func<bool> _moveNext;
  360. private readonly Func<T> _current;
  361. private readonly Action _dispose;
  362. public Enumerator(Func<bool> moveNext, Func<T> current, Action dispose)
  363. {
  364. _moveNext = moveNext;
  365. _current = current;
  366. _dispose = dispose;
  367. }
  368. public T Current
  369. {
  370. get { return _current(); }
  371. }
  372. public void Dispose()
  373. {
  374. _dispose();
  375. }
  376. object IEnumerator.Current
  377. {
  378. get { return Current; }
  379. }
  380. public bool MoveNext()
  381. {
  382. return _moveNext();
  383. }
  384. public void Reset()
  385. {
  386. throw new NotImplementedException();
  387. }
  388. }
  389. }
  390. }