如何封装来自 IEnumerable 的长期延迟的维护项目列表
我有一个枚举需要很长时间才能获得下一个值。
我正在尝试包装该可枚举,以便获得一个缓存结果的可枚举。
我还希望它在另一个线程上进行额外的加载(报告它到达集合的末尾)。即,如果它有 10 个缓存值,并且我枚举它报告 10,然后启动一个线程来获取下一个值,因此当再次枚举时,有 11 个缓存值。
到目前为止,我所拥有的如下(在底部带有测试它的代码):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
public class CachedEnumerable<T> : IEnumerable<T>
{
public class CachedEnumerator : IEnumerator<T>
{
private IEnumerator<T> _UnderlyingEnumerator;
public event EventHandler Disposed;
public CachedEnumerator(IEnumerator<T> UnderlyingEnumerator)
{
_UnderlyingEnumerator = UnderlyingEnumerator;
}
public T Current
{
get { return _UnderlyingEnumerator.Current; }
}
public void Dispose()
{
_UnderlyingEnumerator.Dispose();
if (Disposed != null)
Disposed(this, new EventArgs());
}
object System.Collections.IEnumerator.Current
{
get { return _UnderlyingEnumerator.Current; }
}
public bool MoveNext()
{
return _UnderlyingEnumerator.MoveNext();
}
public void Reset()
{
_UnderlyingEnumerator.Reset();
}
}
// The slow enumerator.
private IEnumerator<T> _SourceEnumerator;
// Whether we're currently already getting the next item.
private bool _GettingNextItem = false;
// Whether we've got to the end of the source enumerator.
private bool _EndOfSourceEnumerator = false;
// The list of values we've got so far.
private List<T> _CachedValues = new List<T>();
// An object to lock against, to protect the cached value list.
private object _CachedValuesLock = new object();
// A reset event to indicate whether the cached list is safe, or whether we're currently enumerating over it.
private ManualResetEvent _CachedValuesSafe = new ManualResetEvent(true);
public CachedEnumerable(IEnumerable<T> Source)
{
_SourceEnumerator = Source.GetEnumerator();
}
private void Enum_Disposed(object sender, EventArgs e)
{
// The cached list is now safe (because we've finished enumerating).
_CachedValuesSafe.Set();
if (!_EndOfSourceEnumerator && !_GettingNextItem)
{
_GettingNextItem = true;
ThreadPool.QueueUserWorkItem((SourceEnumeratorArg) =>
{
var SourceEnumerator = SourceEnumeratorArg as IEnumerator<T>;
if (SourceEnumerator.MoveNext())
{
_CachedValuesSafe.WaitOne(); // Wait for any enumerator to finish
lock (_CachedValuesLock)
{
_CachedValues.Add(SourceEnumerator.Current);
}
}
else
{
_EndOfSourceEnumerator = true;
}
_GettingNextItem = false;
}, _SourceEnumerator);
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
lock (_CachedValuesLock)
{
var Enum = new CachedEnumerator(_CachedValues.GetEnumerator());
Enum.Disposed += new EventHandler(Enum_Disposed);
_CachedValuesSafe.Reset();
return Enum;
}
}
}
class Program
{
public static IEnumerable<int> SlowNumbers()
{
int i = 0;
while (true)
{
Thread.Sleep(1000);
yield return i++;
}
}
static void Main(string[] args)
{
var SlowNumbersEnumerator = new CachedEnumerable<int>(SlowNumbers());
while (true)
{
foreach (var i in SlowNumbersEnumerator)
{
Console.WriteLine(i);
Thread.Sleep(100);
}
}
}
}
}
我的问题是我收到 The collection has been generated
错误,因为工作线程正在将其添加到列表中被列举。但是,通过使用 ManualResetEvent
,我认为我正在防范这种情况。
我做错了什么?
I have an enumerable that takes a long time to get the next value.
I'm trying to wrap that enumerable so that I get an enumerable that caches the results.
I'd also like it to do additional loading on another thread (reporting it reached the end of the collection). i.e. if it has 10 cached values, and i enumerate it reports 10, then starts a thread to get the next one so when enumerated again there's 11 cached values.
What i have so far is below (with code that tests it at the bottom):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
public class CachedEnumerable<T> : IEnumerable<T>
{
public class CachedEnumerator : IEnumerator<T>
{
private IEnumerator<T> _UnderlyingEnumerator;
public event EventHandler Disposed;
public CachedEnumerator(IEnumerator<T> UnderlyingEnumerator)
{
_UnderlyingEnumerator = UnderlyingEnumerator;
}
public T Current
{
get { return _UnderlyingEnumerator.Current; }
}
public void Dispose()
{
_UnderlyingEnumerator.Dispose();
if (Disposed != null)
Disposed(this, new EventArgs());
}
object System.Collections.IEnumerator.Current
{
get { return _UnderlyingEnumerator.Current; }
}
public bool MoveNext()
{
return _UnderlyingEnumerator.MoveNext();
}
public void Reset()
{
_UnderlyingEnumerator.Reset();
}
}
// The slow enumerator.
private IEnumerator<T> _SourceEnumerator;
// Whether we're currently already getting the next item.
private bool _GettingNextItem = false;
// Whether we've got to the end of the source enumerator.
private bool _EndOfSourceEnumerator = false;
// The list of values we've got so far.
private List<T> _CachedValues = new List<T>();
// An object to lock against, to protect the cached value list.
private object _CachedValuesLock = new object();
// A reset event to indicate whether the cached list is safe, or whether we're currently enumerating over it.
private ManualResetEvent _CachedValuesSafe = new ManualResetEvent(true);
public CachedEnumerable(IEnumerable<T> Source)
{
_SourceEnumerator = Source.GetEnumerator();
}
private void Enum_Disposed(object sender, EventArgs e)
{
// The cached list is now safe (because we've finished enumerating).
_CachedValuesSafe.Set();
if (!_EndOfSourceEnumerator && !_GettingNextItem)
{
_GettingNextItem = true;
ThreadPool.QueueUserWorkItem((SourceEnumeratorArg) =>
{
var SourceEnumerator = SourceEnumeratorArg as IEnumerator<T>;
if (SourceEnumerator.MoveNext())
{
_CachedValuesSafe.WaitOne(); // Wait for any enumerator to finish
lock (_CachedValuesLock)
{
_CachedValues.Add(SourceEnumerator.Current);
}
}
else
{
_EndOfSourceEnumerator = true;
}
_GettingNextItem = false;
}, _SourceEnumerator);
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
lock (_CachedValuesLock)
{
var Enum = new CachedEnumerator(_CachedValues.GetEnumerator());
Enum.Disposed += new EventHandler(Enum_Disposed);
_CachedValuesSafe.Reset();
return Enum;
}
}
}
class Program
{
public static IEnumerable<int> SlowNumbers()
{
int i = 0;
while (true)
{
Thread.Sleep(1000);
yield return i++;
}
}
static void Main(string[] args)
{
var SlowNumbersEnumerator = new CachedEnumerable<int>(SlowNumbers());
while (true)
{
foreach (var i in SlowNumbersEnumerator)
{
Console.WriteLine(i);
Thread.Sleep(100);
}
}
}
}
}
My problem is that i get the The collection has been modified
error, because the worker thread is adding to the list while it's being enumerated. However, through my use of a ManualResetEvent
i thought i was guarding against this.
What am i doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
(让我的评论成为答案,无法正确格式化评论)
_CachedValuesSafe.WaitOne();
GetEnumerator()
调用返回并释放锁 |线程 B 获取锁Add
,修改集合(making my comment an answer, no way to format comments correctly)
_CachedValuesSafe.WaitOne();
GetEnumerator()
call and release the lock | Thread B acquire the lockAdd
, modifying the collection