在迭代器块中输入锁

时间:2018-07-27 14:48:48

标签: c# iterator spinlock

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

我有这种方法:

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))
{
    ...
}

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

0 个答案:

没有答案
相关问题