【发布时间】:2009-07-06 15:47:41
【问题描述】:
我创建了ThreadSafeCachedEnumerable<T> 类,旨在提高重复使用长时间运行的查询的性能。这个想法是从IEnumerable<T> 获取一个枚举器,并在每次调用MoveNext() 时将项目添加到缓存中。以下是我目前的实现:
/// <summary>
/// Wraps an IEnumerable<T> and provides a thread-safe means of caching the values."/>
/// </summary>
/// <typeparam name="T"></typeparam>
class ThreadSafeCachedEnumerable<T> : IEnumerable<T>
{
// An enumerator from the original IEnumerable<T>
private IEnumerator<T> enumerator;
// The items we have already cached (from this.enumerator)
private IList<T> cachedItems = new List<T>();
public ThreadSafeCachedEnumerable(IEnumerable<T> enumerable)
{
this.enumerator = enumerable.GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
// The index into the sequence
int currentIndex = 0;
// We will break with yield break
while (true)
{
// The currentIndex will never be decremented,
// so we can check without locking first
if (currentIndex < this.cachedItems.Count)
{
var current = this.cachedItems[currentIndex];
currentIndex += 1;
yield return current;
}
else
{
// If !(currentIndex < this.cachedItems.Count),
// we need to synchronize access to this.enumerator
lock (enumerator)
{
// See if we have more cached items ...
if (currentIndex < this.cachedItems.Count)
{
var current = this.cachedItems[currentIndex];
currentIndex += 1;
yield return current;
}
else
{
// ... otherwise, we'll need to get the next item from this.enumerator.MoveNext()
if (this.enumerator.MoveNext())
{
// capture the current item and cache it, then increment the currentIndex
var current = this.enumerator.Current;
this.cachedItems.Add(current);
currentIndex += 1;
yield return current;
}
else
{
// We reached the end of the enumerator - we're done
yield break;
}
}
}
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
当缓存中似乎没有更多项目时,我只是 lock (this.enumerator),以防另一个线程即将添加另一个项目(我假设从两个线程调用 this.enumerator MoveNext() 是不好的想法)。
在检索以前缓存的项目时性能很好,但在第一次获取许多项目时它开始受到影响(由于不断锁定)。有什么提高性能的建议吗?
编辑:新的Reactive Framework 使用System.Linq.EnumerableEx.MemoizeAll() 扩展方法解决了上述问题。
在内部,MemoizeAll() 使用 System.Linq.EnumerableEx.MemoizeAllEnumerable<T>(在 System.Interactive 程序集中找到),类似于我的 ThreadSafeCachedEnumerable<T>(排序)。
这是一个非常人为的示例,它非常缓慢地打印 Enumerable(数字 1-10)的内容,然后再次快速打印内容(因为它缓存了值):
// Create an Enumerable<int> containing numbers 1-10, using Thread.Sleep() to simulate work
var slowEnum = EnumerableEx.Generate(1, currentNum => (currentNum <= 10), currentNum => currentNum, previousNum => { Thread.Sleep(250); return previousNum + 1; });
// This decorates the slow enumerable with one that will cache each value.
var cachedEnum = slowEnum.MemoizeAll();
// Print the numbers
foreach (var num in cachedEnum.Repeat(2))
{
Console.WriteLine(num);
}
【问题讨论】:
-
我在Rx codebase 中看不到
MemoizeAll或MemoizeAllEnumerable。话虽如此,您的ThreadSafeCachedEnumerable忘记在源枚举器上调用 dispose(),它是一个 IDisposable。这通常是foreach或 Linq 方法的责任,但既然你得到了一个,你应该负责处理它。 -
相关:System.Interactive: Difference between Memoize() and MemoizeAll()。
Memoize运算符的源代码是here。
标签: c# performance multithreading caching ienumerable