首页 > 解决方案 > 在迭代器块中输入锁

问题描述

我很想知道迭代器块是否是锁定的好地方。

我有这个方法:

protected SpinLock readLock;
protected bool readLockTaken;
protected SpinLock writeLock;
protected bool writeLockTaken;

public IEnumerator<T> GetConsumingEnumerator()
{
    readLock.Enter(ref writeLockTaken);

    try
    {
        for (int i = 0; i < queue.Count; i++)
        {
            if(queue.Count != 0)
                yield return queue.Dequeue();
            else
                yield break;
        }
    }
    finally
    {
        readLock.Exit();
    }            
}

我对迭代器块没有太多经验,我想知道锁是否会在这样的语句的持续时间内保持“进入”状态:

foreach(T thing in ThingCollection.GetConsumingEnumerator())
{
    ...
}

另外,如果我使用 LINQ 获取 n 个元素,n < "collection".Count如下所示:

foreach(T thing in ThingCollection.GetConsumingEnumerator().Take(n))
{
    ...
}

访问元素时自旋锁会保持锁定状态吗?还是每次迭代都会退出并重新进入锁?

标签: c#iteratorspinlock

解决方案


推荐阅读