Reputation: 1003
What I want to be able to do is to access a List
on multiple threads. This is thread safe, so I can just do it without worries. The only problem is that occasionally, I must modify the List
. So, I want to prevent other threads from using the List
only when it is being modified.
This is what I'm thinking, is there a better way?
volatile bool isReading = false;
volatile bool isWriting = false;
object o = new object();
public void StartRead()
{
lock (o)
{
while (isWriting || isReading) ;
isReading = true;
}
}
public void StopRead()
{
isReading = false;
}
public void StartWrite()
{
lock (o)
{
while (isReading) ;
isWriting = true;
}
}
public void StopWrite()
{
isWriting = false;
}
Upvotes: 1
Views: 1221
Reputation: 4166
A better solution would be to use a ReaderWriterLockSlim
. This will let you have many readers at the same time, but only lock it when you have a writer.
http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx
This really depends on just how much contention there is for the lock though. In low-contention situations, a lock
will perform similarly to the ReaderWriterLockSlim
- reference When is ReaderWriterLockSlim better than a simple lock?.
There's many possible solutions to this question, depending on a lot of specifics about how it's being used. But, in the simplistic "taken at face value" case, a ReaderWriterLockSlim
is a decent solution. If it doesn't work for you after profiling performance, then other solutions may be needed that accommodate your specific usage scenarios.
Upvotes: 3