AsyncTests.Bugs.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. private readonly CancellationToken cancellationToken;
  214. public CancellationTestEnumerable()
  215. {
  216. }
  217. public IEnumerator<T> GetEnumerator() => new TestEnumerator();
  218. private sealed class TestEnumerator : IEnumerator<T>
  219. {
  220. private readonly CancellationTokenSource cancellationTokenSource;
  221. public TestEnumerator()
  222. {
  223. cancellationTokenSource = new CancellationTokenSource();
  224. }
  225. public void Dispose()
  226. {
  227. cancellationTokenSource.Cancel();
  228. }
  229. public void Reset()
  230. {
  231. }
  232. object IEnumerator.Current => Current;
  233. public T Current { get; }
  234. public bool MoveNext()
  235. {
  236. Task.Delay(WaitTimeoutMs, cancellationTokenSource.Token).Wait();
  237. cancellationTokenSource.Token.ThrowIfCancellationRequested();
  238. return true;
  239. }
  240. }
  241. IEnumerator IEnumerable.GetEnumerator()
  242. {
  243. return GetEnumerator();
  244. }
  245. }
  246. [Fact]
  247. public void ToAsyncEnumeratorCannotCancelOnceRunning()
  248. {
  249. var evt = new ManualResetEvent(false);
  250. var isRunningEvent = new ManualResetEvent(false);
  251. var xs = Blocking(evt, isRunningEvent).ToAsyncEnumerable();
  252. var e = xs.GetEnumerator();
  253. var cts = new CancellationTokenSource();
  254. Task<bool> t = null;
  255. var tMoveNext =Task.Run(
  256. () =>
  257. {
  258. // This call *will* block
  259. t = e.MoveNext(cts.Token);
  260. });
  261. isRunningEvent.WaitOne();
  262. cts.Cancel();
  263. try
  264. {
  265. tMoveNext.Wait(0);
  266. Assert.False(t.IsCanceled);
  267. }
  268. catch
  269. {
  270. // T will still be null
  271. Assert.Null(t);
  272. }
  273. // enable it to finish
  274. evt.Set();
  275. }
  276. static IEnumerable<int> Blocking(ManualResetEvent evt, ManualResetEvent blockingStarted)
  277. {
  278. blockingStarted.Set();
  279. evt.WaitOne();
  280. yield return 42;
  281. }
  282. [Fact]
  283. public async Task TakeOneFromSelectMany()
  284. {
  285. var enumerable = AsyncEnumerable
  286. .Return(0)
  287. .SelectMany(_ => AsyncEnumerable.Return("Check"))
  288. .Take(1)
  289. .Do(_ => { });
  290. Assert.Equal("Check", await enumerable.First());
  291. }
  292. [Fact]
  293. public void SelectManyDisposeInvokedOnlyOnce()
  294. {
  295. var disposeCounter = new DisposeCounter();
  296. var result = AsyncEnumerable.Return(1).SelectMany(i => disposeCounter).Select(i => i).ToList().Result;
  297. Assert.Equal(0, result.Count);
  298. Assert.Equal(1, disposeCounter.DisposeCount);
  299. }
  300. [Fact]
  301. public void SelectManyInnerDispose()
  302. {
  303. var disposes = Enumerable.Range(0, 10).Select(_ => new DisposeCounter()).ToList();
  304. var result = AsyncEnumerable.Range(0, 10).SelectMany(i => disposes[i]).Select(i => i).ToList().Result;
  305. Assert.Equal(0, result.Count);
  306. Assert.True(disposes.All(d => d.DisposeCount == 1));
  307. }
  308. private class DisposeCounter : IAsyncEnumerable<object>
  309. {
  310. public int DisposeCount { get; private set; }
  311. public IAsyncEnumerator<object> GetEnumerator()
  312. {
  313. return new Enumerator(this);
  314. }
  315. private class Enumerator : IAsyncEnumerator<object>
  316. {
  317. private readonly DisposeCounter _disposeCounter;
  318. public Enumerator(DisposeCounter disposeCounter)
  319. {
  320. _disposeCounter = disposeCounter;
  321. }
  322. public void Dispose()
  323. {
  324. _disposeCounter.DisposeCount++;
  325. }
  326. public Task<bool> MoveNext(CancellationToken _)
  327. {
  328. return Task.Factory.StartNew(() => false);
  329. }
  330. public object Current { get; private set; }
  331. }
  332. }
  333. }
  334. static class MyExt
  335. {
  336. public static IEnumerable<T> WithDispose<T>(this IEnumerable<T> source, Action a)
  337. {
  338. return EnumerableEx.Create(() =>
  339. {
  340. var e = source.GetEnumerator();
  341. return new Enumerator<T>(e.MoveNext, () => e.Current, () => { e.Dispose(); a(); });
  342. });
  343. }
  344. public static IAsyncEnumerable<T> WithDispose<T>(this IAsyncEnumerable<T> source, Action a)
  345. {
  346. return AsyncEnumerable.CreateEnumerable<T>(() =>
  347. {
  348. var e = source.GetEnumerator();
  349. return AsyncEnumerable.CreateEnumerator<T>(e.MoveNext, () => e.Current, () => { e.Dispose(); a(); });
  350. });
  351. }
  352. class Enumerator<T> : IEnumerator<T>
  353. {
  354. private readonly Func<bool> _moveNext;
  355. private readonly Func<T> _current;
  356. private readonly Action _dispose;
  357. public Enumerator(Func<bool> moveNext, Func<T> current, Action dispose)
  358. {
  359. _moveNext = moveNext;
  360. _current = current;
  361. _dispose = dispose;
  362. }
  363. public T Current
  364. {
  365. get { return _current(); }
  366. }
  367. public void Dispose()
  368. {
  369. _dispose();
  370. }
  371. object IEnumerator.Current
  372. {
  373. get { return Current; }
  374. }
  375. public bool MoveNext()
  376. {
  377. return _moveNext();
  378. }
  379. public void Reset()
  380. {
  381. throw new NotImplementedException();
  382. }
  383. }
  384. }
  385. }