AsyncEnumerableExecutor.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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.Linq.Expressions;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. /// <summary>
  10. /// Provides functionality to evaluate an expression tree representation of a computation over asynchronous enumerable sequences.
  11. /// </summary>
  12. /// <typeparam name="T">The type of the elements in the sequence.</typeparam>
  13. internal class AsyncEnumerableExecutor<T>
  14. {
  15. private readonly Expression _expression;
  16. private Func<CancellationToken, Task<T>> _func;
  17. /// <summary>
  18. /// Creates a new execution helper instance for the specified expression tree representing a computation over asynchronous enumerable sequences.
  19. /// </summary>
  20. /// <param name="expression">Expression tree representing a computation over asynchronous enumerable sequences.</param>
  21. public AsyncEnumerableExecutor(Expression expression)
  22. {
  23. _expression = expression;
  24. }
  25. /// <summary>
  26. /// Evaluated the expression tree.
  27. /// </summary>
  28. /// <param name="token">Token to cancel the evaluation.</param>
  29. /// <returns>Task representing the evaluation of the expression tree.</returns>
  30. internal Task<T> ExecuteAsync(CancellationToken token)
  31. {
  32. if (_func == null)
  33. {
  34. var expression = Expression.Lambda<Func<CancellationToken, Task<T>>>(new AsyncEnumerableRewriter().Visit(_expression), Expression.Parameter(typeof(CancellationToken)));
  35. _func = expression.Compile();
  36. }
  37. return _func(token);
  38. }
  39. }
  40. }