yield方法释放锁吗_C#Yield是否释放锁?

I have the following method:

public static IEnumerable> 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();

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?

解决方案

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

When the iterator is suspended and Dispose is called the finally blocks in scope at the point of the suspend will run

When the iterator is running and the code would otherwise trigger a finally the finally block runs.

When the iterator encounters a yield break statement the finally blocks in scope at the point of the yield break will run

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值