【问题标题】:Is there an IEnumerable implementation that only iterates over it's source (e.g. LINQ) once?是否有一个 IEnumerable 实现只迭代它的源(例如 LINQ)一次?
【发布时间】:2012-09-14 15:01:49
【问题描述】:

如果items 是 LINQ 表达式的结果:

var items = from item in ItemsSource.RetrieveItems()
            where ...

假设每个项目的生成需要一些不可忽略的时间。

有两种可能的操作模式:

  1. 使用foreach 将允许在集合开始时比最终可用的项目更早地开始处理项目。但是,如果我们想稍后再次处理同一个集合,我们将不得不复制保存它:

    var storedItems = new List<Item>();
    foreach(var item in items)
    {
        Process(item);
        storedItems.Add(item);
    }
    
    // Later
    foreach(var item in storedItems)
    {
        ProcessMore(item);
    }
    

    因为如果我们刚刚创建了foreach(... in items),那么ItemsSource.RetrieveItems() 会再次被调用。

  2. 我们可以直接使用.ToList(),但这会迫使我们等待最后一个项目被检索,然后才能开始处理第一个项目。

问题:是否有 IEnumerable 实现会像常规 LINQ 查询结果一样第一次迭代,但会在处理过程中实现,以便第二次 foreach 会迭代存储的值?

【问题讨论】:

  • 编写一个接收原始 IEnumerable 的 CachingEnumerable/CachingEnumerator 实现有多难,并且枚举器将循环遍历缓存,然后从原始缓存中提取其他值直到完成,并在完成时缓存它?但是不,我不知道有任何框架实现可以做到这一点。
  • @Rich:应该不会太难,就是想看看有没有。
  • 嗯,问题是foreach 实际上与它自己的IEnumerator 一起工作,而IEnumerator 有它自己的状态。当然,您可以将IQueryableIEnumerable 包装在缓存中;但是,您必须处理两个 IEnumerators 以不同速率同时枚举的可能性。
  • 这是典型的情况,我会停止使用 LINQ 来支持标准循环 :) 无论如何,挑战非常有趣。
  • Caching IEnumerable的可能重复

标签: c# .net linq ienumerable


【解决方案1】:

一个有趣的挑战,所以我必须提供自己的解决方案。事实上非常有趣,我的解决方案现在是版本 3。版本 2 是我根据 Servy 的反馈进行的简化。然后我意识到我的解决方案有很大的缺点。如果缓存的可枚举的第一个枚举没有完成,则不会进行缓存。许多 LINQ 扩展,如 FirstTake 只会枚举足够的可枚举来完成工作,我必须更新到版本 3 才能使用缓存。

问题是关于不涉及并发访问的可枚举的后续枚举。尽管如此,我还是决定让我的解决方案线程安全。它增加了一些复杂性和一些开销,但应该允许在所有场景中使用该解决方案。

public static class EnumerableExtensions {

  public static IEnumerable<T> Cached<T>(this IEnumerable<T> source) {
    if (source == null)
      throw new ArgumentNullException("source");
    return new CachedEnumerable<T>(source);
  }

}

class CachedEnumerable<T> : IEnumerable<T> {

  readonly Object gate = new Object();

  readonly IEnumerable<T> source;

  readonly List<T> cache = new List<T>();

  IEnumerator<T> enumerator;

  bool isCacheComplete;

  public CachedEnumerable(IEnumerable<T> source) {
    this.source = source;
  }

  public IEnumerator<T> GetEnumerator() {
    lock (this.gate) {
      if (this.isCacheComplete)
        return this.cache.GetEnumerator();
      if (this.enumerator == null)
        this.enumerator = source.GetEnumerator();
    }
    return GetCacheBuildingEnumerator();
  }

  public IEnumerator<T> GetCacheBuildingEnumerator() {
    var index = 0;
    T item;
    while (TryGetItem(index, out item)) {
      yield return item;
      index += 1;
    }
  }

  bool TryGetItem(Int32 index, out T item) {
    lock (this.gate) {
      if (!IsItemInCache(index)) {
        // The iteration may have completed while waiting for the lock.
        if (this.isCacheComplete) {
          item = default(T);
          return false;
        }
        if (!this.enumerator.MoveNext()) {
          item = default(T);
          this.isCacheComplete = true;
          this.enumerator.Dispose();
          return false;
        }
        this.cache.Add(this.enumerator.Current);
      }
      item = this.cache[index];
      return true;
    }
  }

  bool IsItemInCache(Int32 index) {
    return index < this.cache.Count;
  }

  IEnumerator IEnumerable.GetEnumerator() {
    return GetEnumerator();
  }

}

扩展名是这样使用的(sequenceIEnumerable&lt;T&gt;):

var cachedSequence = sequence.Cached();

// Pulling 2 items from the sequence.
foreach (var item in cachedSequence.Take(2))
  // ...

// Pulling 2 items from the cache and the rest from the source.
foreach (var item in cachedSequence)
  // ...

// Pulling all items from the cache.
foreach (var item in cachedSequence)
  // ...

如果仅枚举部分可枚举(例如cachedSequence.Take(2).ToList()ToList 使用的枚举器将被释放,但底层源枚举器未释放。这是因为前两项是如果对后续项目进行请求,则源枚举器被缓存并且源枚举器保持活动状态。在这种情况下,源枚举器仅在符合垃圾回收条件时才被清理(这将与可能的大缓存相同)。

【讨论】:

  • 如果您使用迭代器块来实现IEnumerator,这会更短/更简单。它将摆脱很多样板代码。
  • @Servy:我已经根据您的输入更新了代码,我认为这是一个很好的简化。
  • 看起来好多了。现在你只需要像我的回答一样允许多线程(缓存)迭代;)
  • @Servy:在我看来,多线程是一个完全不同的问题,需要不同的解决方案(您似乎已经提供了)。我的解决方案解决了您想要调用ToList 以避免重复枚举但您仍然想要IEnumerable&lt;T&gt; 的懒惰的问题。
  • 放弃IDisposable 对象很恶心,虽然我猜因为不知道将来是否会调用GetEnumerator,所以可能没有好方法知道何时可以安全地处理枚举器.太糟糕了,没有一次性枚举的概念。
【解决方案2】:

查看Reactive Extentsions 库 - 有一个MemoizeAll() 扩展程序,一旦访问它们,它将缓存您的 IEnumerable 中的项目,并存储它们以供将来访问。

请参阅 Bart De Smet 的 this 博客文章,详细了解 MemoizeAll 和其他 Rx 方法。

编辑:这实际上可以在单独的交互式扩展包中找到 - 可从 NuGetMicrosoft Download 获得。

【讨论】:

  • 谢谢,这是我这周收到的另一个关于 Rx 的参考。需要时间消化。
【解决方案3】:
public static IEnumerable<T> SingleEnumeration<T>(this IEnumerable<T> source)
{
    return new SingleEnumerator<T>(source);
}

private class SingleEnumerator<T> : IEnumerable<T>
{
    private CacheEntry<T> cacheEntry;
    public SingleEnumerator(IEnumerable<T> sequence)
    {
        cacheEntry = new CacheEntry<T>(sequence.GetEnumerator());
    }

    public IEnumerator<T> GetEnumerator()
    {
        if (cacheEntry.FullyPopulated)
        {
            return cacheEntry.CachedValues.GetEnumerator();
        }
        else
        {
            return iterateSequence<T>(cacheEntry).GetEnumerator();
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

private static IEnumerable<T> iterateSequence<T>(CacheEntry<T> entry)
{
    using (var iterator = entry.CachedValues.GetEnumerator())
    {
        int i = 0;
        while (entry.ensureItemAt(i) && iterator.MoveNext())
        {
            yield return iterator.Current;
            i++;
        }
    }
}

private class CacheEntry<T>
{
    public bool FullyPopulated { get; private set; }
    public ConcurrentQueue<T> CachedValues { get; private set; }

    private static object key = new object();
    private IEnumerator<T> sequence;

    public CacheEntry(IEnumerator<T> sequence)
    {
        this.sequence = sequence;
        CachedValues = new ConcurrentQueue<T>();
    }

    /// <summary>
    /// Ensure that the cache has an item a the provided index.  If not, take an item from the 
    /// input sequence and move to the cache.
    /// 
    /// The method is thread safe.
    /// </summary>
    /// <returns>True if the cache already had enough items or 
    /// an item was moved to the cache, 
    /// false if there were no more items in the sequence.</returns>
    public bool ensureItemAt(int index)
    {
        //if the cache already has the items we don't need to lock to know we 
        //can get it
        if (index < CachedValues.Count)
            return true;
        //if we're done there's no race conditions hwere either
        if (FullyPopulated)
            return false;

        lock (key)
        {
            //re-check the early-exit conditions in case they changed while we were
            //waiting on the lock.

            //we already have the cached item
            if (index < CachedValues.Count)
                return true;
            //we don't have the cached item and there are no uncached items
            if (FullyPopulated)
                return false;

            //we actually need to get the next item from the sequence.
            if (sequence.MoveNext())
            {
                CachedValues.Enqueue(sequence.Current);
                return true;
            }
            else
            {
                FullyPopulated = true;
                return false;
            }
        }
    }
}

所以这已经被编辑(基本上)以支持多线程访问。多个线程可以请求项目,并且在逐个项目的基础上,它们将被缓存。它不需要等待整个序列被迭代以返回缓存值。下面是一个演示这个的示例程序:

private static IEnumerable<int> interestingIntGenertionMethod(int maxValue)
{
    for (int i = 0; i < maxValue; i++)
    {
        Thread.Sleep(1000);
        Console.WriteLine("actually generating value: {0}", i);
        yield return i;
    }
}

public static void Main(string[] args)
{
    IEnumerable<int> sequence = interestingIntGenertionMethod(10)
        .SingleEnumeration();

    int numThreads = 3;
    for (int i = 0; i < numThreads; i++)
    {
        int taskID = i;
        Task.Factory.StartNew(() =>
        {
            foreach (int value in sequence)
            {
                Console.WriteLine("Task: {0} Value:{1}",
                    taskID, value);
            }
        });
    }

    Console.WriteLine("Press any key to exit...");
    Console.ReadKey(true);
}

你真的需要看到它运行才能了解这里的力量。一旦单个线程强制生成下一个实际值,所有剩余的线程都可以立即打印该生成的值,但如果该线程没有未缓存的值要打印,它们都将等待。 (显然线程/线程池调度可能会导致一项任务花费更长的时间来打印它的值。)

【讨论】:

  • 该方法要求第一次枚举完整且完整后才缓存结果。理想情况下,在随后的枚举中,您可以返回 IList&lt;&gt; 以利用 Linq 优化。
  • @Greg 至于您的第一点,这是故意的(只需将cache.Add 移到foreach 之前即可更改)。我不想缓存一半的序列,让另一个线程返回一个半完成的序列,然后让第一个线程稍后完成缓存条目。至于第二点,是的,我可以。这将涉及重新分解为两种方法(您可以在同一方法中获得常规回报和收益回报),我想让它更简单。如果你将else 重构为一个方法,那么if 可以返回一个List
  • @zzandy 完全重写,因此如果您不想提供密钥,则不再需要提供。有一个新的包装器,它将允许迭代多次的可枚举项将缓存的值用于所有后续迭代。如果您只想使用它,请使用 CachedSequence 方法 private
  • @Greg 我在编辑中包含了优化,因为无论如何我都需要重新设计解决方案,无论如何它都不会再简单了。
  • @Servy 最初的问题没有指定您需要处理多线程,所以我认为您的想法没问题,但可以/应该简化。如果您想处理多线程,那么您的代码仍然不完整,如果枚举速度很慢并且您有多个线程同时在同一个变量上启动,那么它们都不会在缓存中找到集合,它们都会因此列举出来源。
【解决方案4】:

Martin Liversage 和 Servy 已经分别发布了 Cached/SingleEnumeration 运算符的线程安全实现,System.Interactive 包中的线程安全 Memoise 运算符也可用。如果不需要线程安全,并且不希望支付线程同步的成本,那么在this question 中有提供不同步的ToCachedEnumerable 实现的答案。所有这些实现的共同点是它们都基于自定义类型。我的挑战是在一个独立的扩展方法(不附加任何条件)中编写一个类似的非同步运算符。这是我的实现:

public static IEnumerable<T> MemoiseNotSynchronized<T>(this IEnumerable<T> source)
{
    // Argument validation omitted
    IEnumerator<T> enumerator = null;
    List<T> buffer = null;
    return Implementation();

    IEnumerable<T> Implementation()
    {
        if (buffer != null && enumerator == null)
        {
            // The source has been fully enumerated
            foreach (var item in buffer) yield return item;
            yield break;
        }

        enumerator ??= source.GetEnumerator();
        buffer ??= new();
        for (int i = 0; ; i = checked(i + 1))
        {
            if (i < buffer.Count)
            {
                yield return buffer[i];
            }
            else if (enumerator.MoveNext())
            {
                Debug.Assert(buffer.Count == i);
                var current = enumerator.Current;
                buffer.Add(current);
                yield return current;
            }
            else
            {
                enumerator.Dispose(); enumerator = null;
                yield break;
            }
        }
    }
}

使用示例:

IEnumerable<Point> points = GetPointsFromDB().MemoiseNotSynchronized();
// Enumerate the 'points' any number of times, on a single thread.
// The data will be fetched from the DB only once.
// The connection with the DB will open when the 'points' is enumerated
// for the first time, partially or fully.
// The connection will stay open until the 'points' is enumerated fully
// for the first time.

测试MemoiseNotSynchronized 运算符on Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2021-10-27
    • 2015-03-29
    • 2020-10-26
    • 1970-01-01
    相关资源
    最近更新 更多