Using.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class EnumerableEx
  11. {
  12. /// <summary>
  13. /// Generates a sequence that's dependent on a resource object whose lifetime is determined by the sequence usage
  14. /// duration.
  15. /// </summary>
  16. /// <typeparam name="TSource">Source element type.</typeparam>
  17. /// <typeparam name="TResource">Resource type.</typeparam>
  18. /// <param name="resourceFactory">Resource factory function.</param>
  19. /// <param name="enumerableFactory">Enumerable factory function, having access to the obtained resource.</param>
  20. /// <returns>Sequence whose use controls the lifetime of the associated obtained resource.</returns>
  21. public static IEnumerable<TSource> Using<TSource, TResource>(Func<TResource> resourceFactory, Func<TResource, IEnumerable<TSource>> enumerableFactory) where TResource : IDisposable
  22. {
  23. if (resourceFactory == null)
  24. throw new ArgumentNullException(nameof(resourceFactory));
  25. if (enumerableFactory == null)
  26. throw new ArgumentNullException(nameof(enumerableFactory));
  27. return Using_(resourceFactory, enumerableFactory);
  28. }
  29. private static IEnumerable<TSource> Using_<TSource, TResource>(Func<TResource> resourceFactory, Func<TResource, IEnumerable<TSource>> enumerableFactory) where TResource : IDisposable
  30. {
  31. using (var res = resourceFactory())
  32. foreach (var item in enumerableFactory(res))
  33. yield return item;
  34. }
  35. }
  36. }