Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7170123
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T15:08:53+00:00 2026-05-28T15:08:53+00:00

I tested this block of code and find that the GetInts method does not

  • 0

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");
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T15:08:54+00:00Added an answer on May 28, 2026 at 3:08 pm

    When I run it, it does disconnect:

    Scroll()
    GetInts connected
    yield 99
    99
    ...snip...
    yield 90
    90
    Scroll() completed
    DataSource Disconnected
    Program End
    

    Note that it would disconnect itself if you were reading to the end of the data; however, you are asking for 100 ints, and scrolling through 10 of them; as fas as the iterator is concerned you’ve left it hanging 10% in. If you exhaust an iterator block, it cleans up any using etc; if you don’t exhaust it, it needs to be explicitly disposed. You can illustrate this by changing it to GetInts(5) (leaving all other code the same):

    Scroll()
    GetInts connected
    yield 4
    4
    yield 3
    3
    yield 2
    2
    yield 1
    1
    yield 0
    0
    DataSource Disconnected
    GetInts disconnected
    Scroll() completed
    Program End
    

    The reason it doesn’t show “GetInts disconnected” otherwise is that … it never gets there unless you exhaust it! That is what your code says: “print connected; yield i items; print disconnected” – it won’t print disconnected unless it has first done all the yields. If you use a finally though (using the GetInts(100) again), then this changes:

        static IEnumerable<int> GetInts(int i)
        {
            Console.WriteLine("GetInts connected");
            try
            {
                using (var ds = new DataSourceWrapper())
                {
                    while (i-- != 0)
                    {
                        Console.WriteLine("yield {0}", i);
                        yield return i;
                    }
                }
            }
            finally
            {
                // not called! 
                Console.WriteLine("GetInts disconnected");
            }
        }
    

    Then it works:

    ...
    yield 90
    90
    Scroll() completed
    DataSource Disconnected
    GetInts disconnected
    Program End
    

    Basically, finally is mapped into the Dispose() of the iterator.

    Additionally, _mIter is IEnumerator<T>; it explicitly implements IDisposable, and you are responsible for calling Dispose() at some point. Do that, and it will all work. Even with IEnumerator (non-generic, not explicitly IDisposable) you should follow the same approach as the compiler, and check if the enumerator is IDisposable, and call Dispose() accordingly.

    Since you aren’t consuming the data in one chunk, you can’t use using, but you must still dispose it. This might mean making your type implement IDisposable, and passing along the call. Also, you might want to explicitly dispose and release the enumerator when you reach the end. I can’t really change your code to illustrate this, as it doesn’t make sense on static data, but I would hope that an enumerator would not be static on real code anyway.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This code does not work, returning the error: BEGIN CREATE VIEW [dbo].[dummy] AS SELECT
I believe this works, I've tested it with multiple concurrent threads (though not exhaustively
Hi I have some code that uses block RandomAccessFile file = new RandomAccessFile(some file,
Why does the following code print ‘read(): Resource temporarily unavailable’ 80% of the time?
I have tested this servlet and it works well, except in Google Chrome it
I have this regex I built and tested in regex buddy. _ [ 0-9]{10}+
I know this particular query works, as I tested it with unprepared, procedural methods.
I run into this quite often where a new page is supposedly tested and
The offending block of code is below. The code almost always works, but sometimes
I have some code that retrieves a scripted svg image from a server via

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.