AsyncEnumerableExecutor.cs 1.7 KB

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