Question

I tested this block of code and find that the GetInts method does not exit the method and print "GetInts disconnected" as i would expect, traditionally. I want to write a scroll control that incrementally downloads datarows from the database with yield return, but I am unsure of the correct method.

On the other hand, wrapping the yield return block with using block will guarantee the call on dispose(), but should I go that way?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
    class Program
    {
        static IEnumerator<int> _mIter;

        static void Main(string[] args)
        {
            // get an enumerator to enumerate values in the database, at a later time
            _mIter = GetInts(100).GetEnumerator();

            // simulate some scrolling, which will add values to my scroll box
            Scroll(10);

            // suppose this control is now redundant,
            // but this does not disconnect the data source 
            _mIter.Dispose();

            // program ends will connection still open?
            Console.WriteLine("Program End");
        }
        // iterate and cache (not implemented) values
        private static void Scroll(int units)
        {
            Console.WriteLine("Scroll()");

            while(units-- != 0 && _mIter.MoveNext())
            {
                Console.WriteLine(_mIter.Current);
            }

            Console.WriteLine("Scroll() completed");
        }
        // connect to database, yield-return each datarow, and disconnect (hopefully)
        static IEnumerable<int> GetInts(int i)
        {
            Console.WriteLine("GetInts connected");

            using (var ds = new DataSourceWrapper())
            {
                while (i-- != 0)
                {
                    Console.WriteLine("yield {0}", i);
                    yield return i;
                }
            }

            // not called! 
            Console.WriteLine("GetInts disconnected");
        }
    }
    // try using a datasource wrapper to ensure Dispose() is called to disconnect the connection.
    public class DataSourceWrapper : IDisposable
    {
        public void Dispose()
        {
            Console.WriteLine("DataSource Disconnected");
        }
    }
}

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top