0

Imagine you have the following code:

public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        foreach (Product product in products)
        {
            yield return product;
        }
    }
}

Then in some other place in your code you have the following:

foreach(var p in GetAllProducts())
{ 
    FunctionWhichProcessProductForTenSeconds(p);
    FunctionWhichProcessProductForTwentySeconds(p);
}

does it mean that during all period of execution of foreach(var p in GetAllProducts()) connection to database will remain open?

Yuriy Zaletskyy
  • 4,983
  • 5
  • 34
  • 54
  • 2
    see here: http://stackoverflow.com/questions/5716350/yield-return-inside-usings and here http://stackoverflow.com/questions/1539114/yield-return-statement-inside-a-using-block-disposes-before-executing – Ric Aug 26 '15 at 12:21
  • 5
    Yes it does. If this is a problem, then you can loop on `GetAllProducts().ToList()` instead to fetch all the rows at once and have the connection closed sooner. You'll need to consider the pros and cons. – sstan Aug 26 '15 at 12:30

0 Answers0