I have the following code:
private static object _dbLock = new object();
public static void LoadData()
{
lock (_dbLock)
{
//Load data from the database
}
}
public static string ReadData(Guid key)
{
lock (_dbLock)
{
//Lookup key in data and return value
}
}
I don’t want to allow people to read the data while it’s being loaded from the database, thus I put a lock in ReadData. However, right now if multiple people call ReadData at the same time, only one call can run at once.
Is there a way I can allow simultaneous calls to ReadData but block readers when LoadData is being run?
The
ReaderWriterLockandReaderWriterLockSlimclasses support that use case. Use the ‘Slim’ version unless you need pre-3.5 support.