如何封装来自 IEnumerable 的长期延迟的维护项目列表

发布于 2024-11-24 23:59:18 字数 4814 浏览 0 评论 0原文

我有一个枚举需要很长时间才能获得下一个值。

我正在尝试包装该可枚举,以便获得一个缓存结果的可枚举。

我还希望它在另一个线程上进行额外的加载(报告它到达集合的末尾)。即,如果它有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不忘初心 2024-12-01 23:59:18

(让我的评论成为答案,无法正确格式化评论)

  1. 线程 A 正在枚举 |线程 B 处于 _CachedValuesSafe.WaitOne();
  2. 线程 A 完成枚举(释放 WaitHandle)
  3. 线程 A 开始新的枚举获取锁 |线程 B 想要获取锁
  4. 线程 A 初始化枚举|线程 B 等待锁
  5. 线程 A 从 GetEnumerator() 调用返回并释放锁 |线程 B 获取锁
  6. 线程 A 正在枚举集合 |线程B执行Add,修改集合
  7. 线程A枚举下一个值并抛出异常

(making my comment an answer, no way to format comments correctly)

  1. Thread A is enumerating | Thread B is on _CachedValuesSafe.WaitOne();
  2. Thread A finish enumerating (releasing the WaitHandle)
  3. Thread A started a new enumeration getting the lock | Thread B want to aquire lock
  4. Thread A initialize the enumeration| Thread B wait for the lock
  5. Thread A return from the GetEnumerator() call and release the lock | Thread B acquire the lock
  6. Thread A is enumerating the collection | Thread B execute Add, modifying the collection
  7. Thread A enumerate the next value and throw an exception
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文