AsyncTests.Bugs.cs 14 KB

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