C# - 只允许一个锁处理,使所有其他锁等待,但然后退出而不执行

时间:2013-06-17 18:54:58

标签: .net multithreading locking

我有一个多个用户可以调用的进程。这是一个非常昂贵的查询,但它应该只需要每5分钟左右运行一次以刷新一些存档数据。我现在有一个锁,所以我们不会一次多次运行这个过程,这会使系统瘫痪,但每个用户必须等待之前的锁运行才能运行。如果有3-4个用户等待锁定,则第4个用户必须等待20分钟以上才能运行查询。

我想要做的是锁定此对象并在第一个请求上运行查询。如果有任何其他请求进入,请让他们等待当前锁完成,然后返回而不实际执行查询。

.Net中是否有可以实现此目的的内容,或者我是否需要为此锁写一些特定的代码?

2 个答案:

答案 0 :(得分:2)

您可以使用ManualResetEvent和锁定来执行此操作。

private object _dataLock = new object();
private ManualResetEvent _dataEvent = new ManualResetEvent(false);

private ArchiveData GetData()
{
    if (Monitor.TryEnter(_dataLock))
    {
        _dataEvent.Reset();  // makes other threads wait on the data

        // perform the query

        // then set event to say that data is available
        _dataEvent.Set();
        try
        {
            return data;
        }
        finally
        {
            Monitor.Exit(_dataLock);
        }
    }

    // Other threads wait on the event before returning data.
    _dataEvent.WaitOne();
    return data;
}

所以第一个到达那里的线程获得锁并清除_dataEvent,表明其他线程必须等待数据。这里有一个竞争条件,如果第二个客户端在重置_dataEvent之前到达那里,它将返回旧数据。我认为这是可以接受的,考虑到它的存档数据和发生这种情况的机会窗口非常小。

其他线程尝试获取锁定,失败并被WaitOne阻止。

当数据可用时,执行查询的线程会设置事件,释放锁定并返回数据。

请注意,我没有将整个锁体放在try...finally中。请参阅Eric Lippert的Locks and Exceptions do not mix了解原因。

答案 1 :(得分:2)

此解决方案适用于那些不能接受多个呼叫者执行"准备代码"的可能性的人。

这种技术避免了使用锁定正常"用于编制数据的用例场景。锁定确实有一些开销。哪些可能适用于您的用例,也可能不适用。

该模式称为if-lock-if模式,IIRC。我试图尽可能地注释内联:

bool dataReady;
string data;
object lock = new object();

void GetData()
{
    // The first if-check will only allow a few through. 
    // Normally maybe only one, but when there's a race condition 
    // there might be more of them that enters the if-block. 
    // After the data is ready though the callers will never go into the block, 
    // thus avoids the 'expensive' lock.
    if (!dataReady)
    {
        // The first callers that all detected that there where no data now
        // competes for the lock. But, only one can take it. The other ones
        // will have to wait before they can enter. 
        Monitor.Enter(lock);
        try
        {
            // We know that only one caller at the time is running this code
            // but, since all of the callers waiting for the lock eventually
            // will get here, we have to check if the data is still not ready.
            // The data could have been prepared by the previous caller,
            // making it unnecessary for the next callers to enter.
            if (!dataReady)
            { 
                // The first caller that gets through can now prepare and 
                // get the data, so that it is available for all callers.
                // Only the first caller that gets the lock will execute this code.
                data = "Example data";

                // Since the data has now been prepared we must tell any other callers that
                // the data is ready. We do this by setting the 
                // dataReady flag to true.
                Console.WriteLine("Data prepared!");
                dataReady = true;
            }
        }
        finally
        {
            // This is done in try/finally to ensure that an equal amount of 
            // Monitor.Exit() and Monitor.Enter() calls are executed. 
            // Which is important - to avoid any callers being left outside the lock. 
            Monitor.Exit(lock);
        }
    }

    // This is the part of the code that eventually all callers will execute,
    // as soon as the first caller into the lock has prepared the data for the others.
    Console.WriteLine("Data is: '{0}'", data);
}

MSDN参考: