32

I have the following method:

public static IEnumerable<Dictionary<string, object>> GetRowsIter
   (this SqlCeResultSet resultSet)
{
    // Make sure we don't multi thread the database.
    lock (Database)
    {
        if (resultSet.HasRows)
        {
            resultSet.Read();

            do
            {
                var resultList = new Dictionary<string, object>();
                for (int i = 0; i < resultSet.FieldCount; i++)
                {
                    var value = resultSet.GetValue(i);
                    resultList.Add(resultSet.GetName(i), value == DBNull.Value 
                                                                  ? null : value);
                }
                yield return resultList;
            } while (resultSet.Read());
        }
        yield break;
    }

I just added the lock(Database) to try and get rid of some concurancy issues. I am curious though, will the yield return free the lock on Database and then re-lock when it goes for the next iteration? Or will Database remain locked for the entire duration of the iteration?

Ben McCormack
  • 32,086
  • 48
  • 148
  • 223
Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • 1
    See “And `finally`…” in http://csharpindepth.com/Articles/Chapter6/IteratorBlockImplementation.aspx – Josh Lee Jan 05 '11 at 19:18
  • 7
    This is a potentially *extremely bad idea*. It is very difficult to control lock ordering when you can run arbitrary code between when the lock is obtained and the lock is released. This is just asking for deadlocks. – Eric Lippert Jan 05 '11 at 21:23
  • @Eric Lippert - I am not really too familiar with multithreaded coding. (Though I am getting better as I go.) I now know that the "magic" of the lock statement is really just a `try finally` block and that `yield` keeps things in scope while it is in a yielded state. With this in mind moved the lock to surround just the `for` loop. That gives me the restriction on the SQL Server CE access that I need while not locking during "off" iteration time. (At least so I hope!) – Vaccano Jan 05 '11 at 21:27
  • 3
    To add to Eric's comment: it's even possible that the code that acquires the lock may run in a different thread from the code that (tries to) releases it. – R. Martinho Fernandes Jan 06 '11 at 19:25

4 Answers4

21

No the yield return will not cause any locks to be freed / unlocked. The lock statement will expand out to a try / finally block and the iterator will not treat this any differently than an explicit try / finally in the iterator method.

The details are a bit more complicated but the basic rules for when a finally block will run inside an iterator method is

  1. When the iterator is suspended and Dispose is called the finally blocks in scope at the point of the suspend will run
  2. When the iterator is running and the code would otherwise trigger a finally the finally block runs.
  3. When the iterator encounters a yield break statement the finally blocks in scope at the point of the yield break will run
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • @Marc made the answer more explicit that it would be handled no differently than any other `try / finally` defined in an iterator method. – JaredPar Jan 05 '11 at 19:19
  • @Marc yeah edited to make my intent more explicit after I read your comment. – JaredPar Jan 05 '11 at 19:22
  • Would moving the lock to only bracket the `for` loop "fix" it so that it would lock and unlock after each iteration? – Vaccano Jan 05 '11 at 19:27
  • 1
    @Vaccano that would prevent the lock from being held while the iterator was suspended. Whether or not that is OK for your application is difficult / impossible to determine without better understanding why the lock exists at all – JaredPar Jan 05 '11 at 19:45
14

The lock translates to try/finally (normal C#).

In Iterator blocks (aka yield), "finally" becomes part of the IDisposable.Dispose() implementation of the enumerator. This code is also invoked internally when you consume the last of the data.

"foreach" automatically calls Dispose(), so if you consume with "foreach" (or regular LINQ etc), it will get unlocked.

However, if the caller uses GetEnumerator() directly (very rare) and doesn't read all the data and doesn't call Dispose(), then the lock will not be released.

I would have to check to see if it gets a finaliser; it might get released by GC, but I wouldn't bet money on it.

Pang
  • 9,564
  • 146
  • 81
  • 122
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
5

The Database object will be locked until iteration finishes (or the iterator is disposed).

This might lead to excessive periods of locking, and I would recommend against doing it like this.

driis
  • 161,458
  • 45
  • 265
  • 341
2

The lock remains in effect until you get outside of the scope of lock(). Yielding does not do that.

Otávio Décio
  • 73,752
  • 17
  • 161
  • 228