此解决方案适用于那些不能接受多个调用者执行“准备代码”的可能性的人。
这种技术避免了在数据准备好的“正常”用例场景中使用锁。锁定确实有一些开销。这可能适用于您的用例,也可能不适用于您的用例。
该模式称为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 参考: